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);** }
Try explicitly setting the ID of the control you generate:
You’re getting the null reference exception because no control with the specified ID is being found, so
FindControlis returningnull, and you can’t get theTextproperty of anull.