C#,FindControl

对不起,但我不明白为什么这不起作用。 编译后,我收到一个“空引用exception”。 请帮忙。

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 = "The text you entered was: " + TextBox1.Text + "."; } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Label Label1 = (Label)Master.FindControl("Label1"); Label1.Text = "You chose " + DropDownList1.SelectedValue + " from the dropdown menu."; } } 

和用户界面:

     Type in text and then click button to display text in a Label that is in the MasterPage.
This is done using FindControl.


Choose an item from the below list and it will be displayed in the Label that is in the MasterPage.
This is done using FindControl.
Item 1 Item 2 Item 3

由阿特伍德先生亲自提供 ,这是该方法的递归版本。 我还建议在控件上测试null,并且我还包括如何更改代码来执行此操作。

 protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text != "") { Label Label1 = FindControlRecursive(Page, "Label1") as Label; if(Label1 != null) Label1.Text = "The text you entered was: " + TextBox1.Text + "."; } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Label Label1 = FindControlRecursive(Page, "Label1") as Label; if (Label1 != null) Label1.Text = "You chose " + DropDownList1.SelectedValue + " from the dropdown menu."; } 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; } 

当母版页上存在Label1时:

如何告诉主页面所在的内容页面

 <%@ MasterType VirtualPath="~/MasterPages/PublicUI.Master" %> 

然后在主人身上制作一个方法

 public void SetMessage(string message) { Label1.Text = message; } 

并在页面的代码后面调用它。

 Master.SetMessage("You chose " + DropDownList1.SelectedValue + " from the dropdown menu."); 

当Label1存在于内容页面上时

如果它只是在同一页面上,只需调用Label1.Text = someString; 或者如果由于某种原因需要使用FindControl,请将Master.FindControl更改为FindControl

FindControl只搜索直接子节点(技术上搜索下一个NamingContainer ),而不是整个控制树。 由于Label1不是Master的直接子项,因此Master.FindControl将无法找到它。 相反,您需要在直接父控件上执行FindControl ,或者执行递归控件搜索:

 private Control FindControlRecursive(Control ctrl, string id) { if(ctrl.ID == id) { return ctrl; } foreach (Control child in ctrl.Controls) { Control t = FindControlRecursive(child, id); if (t != null) { return t; } } return null; } 

(注意这是一种方便的扩展方法 )。