EverTheLearner
EverTheLearner

Reputation: 7200

Trouble using findcontrol to find values from dynamic Literal Control

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.

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

Upvotes: 0

Views: 5129

Answers (1)

Daniel LeCheminant
Daniel LeCheminant

Reputation: 51081

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.

Upvotes: 2

Related Questions