.FindControl always returns null

oteal picture oteal · Aug 22, 2012 · Viewed 13.2k times · Source

I have two methods. The first creates one table dynamically, and I add that table into a PlaceHolder.

private void generateData(){
    Table tbl = new Table();
    tbl.ID = "table1";
    holder_info.Controls.Add(tbl);
    // ...adding tr's and td's....
    // ...adding CheckBox in tds....
}

If I do .FindControl("...") inside this method I can find the control using:

CheckBox check = (CheckBox)holder_info.FindControl("checkbox1");

It's OK, but not what I pretend.

In the second method, I want to check whether the user checked checkBox and did something, but I can't find the control (it always returns null).

protected void saveInfo_Click(object sender, ImageClickEventArgs e)
{
  CheckBox check = (CheckBox)holder_info.FindControl("checkbox1");
  if(check.checked){ ... }
}

Also, if I try to find the control "table1", I get null.

Why does this happen?

Answer

Pranay Rana picture Pranay Rana · Aug 22, 2012

It's because you are adding a control dynamically to page, and when you click on the button page get a postback and remove the dynamically added controls. That is why it's not able to find the checkbox control in the button click event.

For dynamic controls, check the article Retaining State for Dynamically Created Controls in ASP.NET applications (The Code Project).