Findcontrol does not find a dynamically added control that just added one line before

who can explain this to me?

CheckBox ckRequest = new CheckBox();
ckRequest.ID = "ckRequest";
ckRequest.DataBinding += new EventHandler(this.CkIsRequested_DataBinding);
container.Controls.Add(ckRequest);
Control con = container.FindControl("ckRequest");

      

Debugging shows con is still null.

Debugging also shows me that conteiner.Controls contains one element with id "ckRequest"

How can it be?


Thanks a lot for your answers.

I actually try the following. findcontrol does not find dynamically created control in rowUpdating event handler It makes sense to me that findcontrol only works on the generated page.

At what point in time is the page's visual tree created?

+3


source to share


3 answers


FindControl

works only when the control is in the visual tree of the page

In your case, you can try this



var checkBoxesInContainer = container.Controls.OfType<CheckBox>();

      

http://msdn.microsoft.com/en-us/library/bb360913.aspx

+3


source


You can use the following:



Control con = 
    container.Controls.Cast<Control>().First(item => item.ID == "ckRequest");

      

+1


source


You might want to try the following:

//GET THE CHECKBOXLIST
Control c = phCategories.Controls.Cast<Control>().First(item => item.ID == "cblCatID-" + catID && item.GetType().Name == "CheckBoxList");
if (c.GetType().Name == "CheckBoxList")
{
  cbl = (CheckBoxList)c;
}

      

For some reason I needed to do this as a control first. If I didn't, it felt like I took the shortcut instead (which didn't make sense to me because it was actually missing the shortcut). Hope this helps someone.

0


source







All Articles