FindControl Issues and Dynamically Generated Controls

Code example:

var div = new HtmlGenericControl("div"); div.Controls.Add(new Literal() { ID = "litSomeLit" }); var lit = (Literal)div.FindControl("litSomeLit"); Assert.IsNotNull(lit); 

This code does not execute the statement because it is null. Debugging shows that div.Controls definitely contains a literal with the identifier "litSomeLit". My questions are: "Why?" and "Is there a way to gain control over a specific identifier without doing a recursive search for div.Controls [] manually one item at a time?"

The reason I am doing this is because my actual application is not so simple - the method I write gets complex control with several subcontrols in a number of possible configurations. I need to access a specific control over several layers (for example, a control with the identifier "txtSpecificControl" can be in StartingControl.Controls[0].Controls[2].Controls[1].Controls[3] ). Usually I could just do FindControl("txtSpecificControl") , but this does not work when the controls are simply dynamically created (as in the above code example).

+4
source share
3 answers

Nearby, as I can tell, there is no way to do what I'm trying to accomplish without adding a control to the page. If I were to guess, I would say that FindControl uses the UniqueID property of the control, which usually contains the identifiers of all the controls over the current one (for example, OuterControlID $ LowerControlId $ TargetControlID). This will only be generated when the control is actually added to the page.

In any case, the implementation of the FindControl recursive search is implemented with a search depth that will work when the control is not yet attached to the page:

  public static Control FindControl(Control parent, string id) { foreach (Control control in parent.Controls) { if (control.ID == id) { return control; } var childResult = FindControl(control, id); if (childResult != null) { return childResult; } } return null; } 
+4
source

Change your code to

 var div = new HtmlGenericControl("div"); Page.Controls.Add(div); div.Controls.Add(new Literal() { ID = "litSomeLit" }); var lit = (Literal)div.FindControl("litSomeLit"); 

As far as I know, FindControl only works when the control is in the visual tree of the page.

+2
source

When you confirmed that the control is in the Controls collection, did you do this by checking the collection directly? FindControl () may not work in this context.

When you debug a test, is it var lit null? If so, you may need to access the by by item instead of using the FindControl () method.

0
source

All Articles