2009-09-22 16 views
8

Lo siento, pero no puedo entender por qué esto no funciona. Después de la compilación, recibo una "excepción de referencia nula". Por favor ayuda.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>"; 
    } 
} 

y la interfaz de usuario:

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

¿Dónde se obtiene la excepción de referencia nula? – Joren

+0

Label1.Text = "Elegiste " + DropDownList1.SelectedValue + " en el menú desplegable"; – AlexC

+0

Posible duplicado http://stackoverflow.com/questions/799655/asp-net-findcontrol-is-not-working-how-come –

Respuesta

22

Cortesía de Mr. Atwood himself, aquí hay una versión recursiva del método. También recomendaría probar nulo en el control e incluí cómo puedes cambiar el código para hacer eso también.

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

Muchas gracias !!!!!!! – AlexC

+2

Bueno para cuando se necesita usar FindControl, pero en el ejemplo de esta pregunta, FindControl es excesivo. – CRice

2

FindControl, solo podrá buscar en los hijos inmediatos (técnicamente a la siguiente NamingContainer), no todo el árbol de control. Como Label1 no es un hijo inmediato de Master, Master.FindControl no lo encontrará. En su lugar, o bien tiene que hacer FindControl en el control de los padres inmediata, o hacer una búsqueda recursiva de control:

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

(Tenga en cuenta que esto es conveniente como un extension method).

3

Cuando Label1 existe en la página principal:

¿Qué dice la página de contenido en su página maestra es

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

luego hacer un método en el maestro como

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

Y llámalo en el código de la página detrás.

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

Cuando Label1 existe en la página de contenido

Si es simplemente en la misma página, simplemente llame Label1.Text = someString; o si por alguna razón necesita utilizar FindControl, cambie su Master.FindControl a FindControl

+0

+1, borré mi respuesta. Esta es una forma mucho más fácil de lograr lo que quieres. – Kelsey