tags:

views:

923

answers:

1

Hi stackoverflow, I'm having problems with finding my controls in my dynamically created literal control. I want to be able to grab the value in the label with the fnameID(x) id. Any help would be appreciated. Thanks!

ASPX:

<div>
  <asp:Panel ID="Panel1" runat="server">
  </asp:Panel>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" 
    onclick="Button1_Click" />

CODE BEHIND:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        CheckBox _checkbox = new CheckBox();
        _checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
        Panel1.Controls.Add(_checkbox);
        Panel1.Controls.Add(new LiteralControl("<Label id='fnameID" 
            + i + "' >test" + i + "</Label><br/>"));
    }

}

protected void Button1_Click(object sender, EventArgs e)
{
    Label lbl = (Label)Panel1.FindControl("fnameID0");
    Response.Write(lbl.Text);
}

Currently I am getting the following error when I click on the button: Object reference not set to an instance of an object.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

{ Label lbl = (Label)Page.FindControl("fnameID0"); Response.Write(lbl.Text); }

+1  A: 

Try explicitly setting the ID of the control you generate:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 50; i++)
    {
        CheckBox _checkbox = new CheckBox();
        _checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
        Panel1.Controls.Add(_checkbox);

        LiteralControl dynLabel = new LiteralControl("<Label id='fnameID" 
            + i + "' >test" + i + "</Label><br/>");
        dynLabel.ID = "fnameID" + i.ToString();

        Panel1.Controls.Add(dynLabel);
    }

}

You're getting the null reference exception because no control with the specified ID is being found, so FindControl is returning null, and you can't get the Text property of a null.

Daniel LeCheminant
You are right. I missed that. Answer deleted.
Daniel Auger
Thanks Daniel. This helped immensely!
Roy