I’ve written a small extention method for a page control, to recursively search for a control. But I get the “Object reference not set to an instance of an object” exception.
And it seems page.Controls only has 1 control and on this control I et this exception.
Anyone has any idea?
Here is the code:
public static Control FindControlRecursive(this Page page, string id)
{
return Execute(page, id);
}
private static Control Execute(Control root, string id)
{
if (root.ID.Equals(id))
return root;
ControlCollection controls = root.Controls;
foreach (Control ctrl in controls)
{
Control FoundControl = Execute(ctrl, id);
if (FoundControl != null)
return FoundControl;
}
return null;
}
}
Update
Now I have another error:
Error occured: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index …
But this one throws somewhere in middle of the looping.
There is one possible cause in this line:
ID property is not necessary set for all controls in the tree. I even doubt whether it is not null for Page itself. Try replacing this line with something like: