findcontrol does not find dynamically added control which was just addes one line before

StackOverflow https://stackoverflow.com/questions/14873069

  •  09-03-2022
  •  | 
  •  

Domanda

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 that con is still null.

Debugging also shows me, that conteiner.Controls hase one Item with ID "ckRequest"

How can this be????


Many thanks for your answers.

Actually I try the following. findcontrol does not find dynamically created control in rowUpdating eventhandler It makes sense to me, that findcontrol works only on the created page.

At which point in time the visual tree of the page is created?

È stato utile?

Soluzione

FindControl only works 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

Altri suggerimenti

You can use the following:

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

You might want to try to 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 cast this as a control first. If I did not do it this way, I seemed to grab a label instead (which didn't make sense to me, because it wasn't actually grabbing a label). Hope it helps somebody.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top