2009-09-22 2 views
8

Извините, но я не понимаю, почему это не работает. После компиляции я получаю «Null reference exception». Пожалуйста помоги.C#, FindControl

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>"; 
    } 
} 

и пользовательский интерфейс:

<%@ 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> 
+0

Где вы можете получить исключение для ссылки? – Joren

+0

Label1.Text = "Вы выбрали " + DropDownList1.SelectedValue + " из выпадающего меню."; – AlexC

+0

Возможный дубликат http://stackoverflow.com/questions/799655/asp-net-findcontrol-is-not-working-how-come –

ответ

22

Предоставлено Mr. Atwood himself, вот рекурсивная версия метода. Я бы также рекомендовал проверить значение 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; 
} 
+0

Спасибо большое !!!!!!! – AlexC

+2

Хорошо, когда нужно использовать FindControl, но в этом вопросе пример FindControl переполнен. – CRice

2

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; 
} 

(Обратите внимание, это удобно как extension method).

3

Когда Label1 существует на главной странице:

Как рассказывать страницу содержания, где ваша главная страница является

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

Затем делает метод в мастера, как

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

И назовите это в коде страницы.

Master.SetMessage("<b>You chose <u>" + DropDownList1.SelectedValue + "</u> from the dropdown menu.</b>"); 

Когда Label1 существует на странице

содержимого Если это просто на той же странице, просто вызовите Label1.Text = SomeString; , или если вам по какой-то причине необходимо использовать FindControl, измените свой Master.FindControl на FindControl

+0

+1, удалил мой ответ. Это гораздо более простой способ выполнить то, что вы хотите. – Kelsey