I am generating 10 labels on fly from code behind and I can see them when i run the page. But its giving an error when i try to access the label.text property. Its giving this error System.NullReferenceException: Object reference not set to an instance of an object.
for (int hf = 1; hf <= dfta2.Rows.Count; hf++)
{
Label lbl = new Label();
lbl.ID = "labeltest" + hf;
lbl.Text = "1";
lbl.ClientIDMode = System.Web.UI.ClientIDMode.Static;
form1.Controls.Add(lbl);
}
string variable3 = "labeltest" + i;
Label lbl2 = form1.FindControl(variable3) as Label;
lbl2.Text = "2";
i is just incremented by 1 every time I click the button. Any idea why its null ?
The code you’ve posted must be placed inside the Page_Load or Page_Init event and verify the value of variable i.
just try,