C#,FindControl [重复]

2024-02-25

抱歉,但我不明白为什么这不起作用。编译后,我收到“空引用异常”。请帮忙。

public partial class labs_test : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text != "")
        {
            Label Label1 = (Label)Master.FindControl("Label1");
            Label1.Text = "<b>The text you entered was: " + TextBox1.Text + ".</b>";
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label Label1 = (Label)Master.FindControl("Label1");
        Label1.Text = "<b>You chose <u>" + DropDownList1.SelectedValue + "</u> from the dropdown menu.</b>";
    }
}

and UI:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="labs_test" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
Type in text and then click button to display text in a Label that is in the MasterPage.<br />
This is done using FindControl.<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /><br />
<br />
Choose an item from the below list and it will be displayed in the Label that is
in the MasterPage.<br />
This is done using FindControl.<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>    
</asp:Content>

致谢阿特伍德先生本人 https://web.archive.org/web/20140218055011/http://www.codinghorror.com:80/blog/2005/06/recursive-pagefindcontrol.html,这是该方法的递归版本。我还建议在控件上测试 null ,并且我还介绍了如何更改代码来执行此操作。

protected void Button1_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != "")
    {
        Label Label1 = FindControlRecursive(Page, "Label1") as Label;
        if(Label1 != null)
            Label1.Text = "<b>The text you entered was: " + TextBox1.Text + ".</b>";
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label Label1 = FindControlRecursive(Page, "Label1") as Label;
    if (Label1 != null)
        Label1.Text = "<b>You chose <u>" + DropDownList1.SelectedValue + "</u> from the dropdown menu.</b>";
}

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id) return root;
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null) return t;
    }
    return null;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C#,FindControl [重复] 的相关文章

随机推荐