Solution to the FindControl problem

I have seen may posts about having problems with the FindControl method. Most seem to come about because the control being searched for is nested within a container other than the webform.

I came across this code (sorry dont remember the web site)  that I have posted in response to many of the posts related to this type of problem. I thought it would be easier if I post this code here for others to find.

/// <summary>

/// Finds a Control recursively. Note finds the first match that exists

/// </summary>

/// <param name=”ContainerCtl”>Should be the lowest container in the heirarchy, for eg dont choose Master page if you can pick the specific panel</param>

/// <param name=”IdToFind”>ID of the control you are looking for</param>

/// <returns>the control if found else null</returns>

private static Control FindControlRecursive(Control Root, string Id)

{

if (Root.ID == Id)

return Root;

foreach (Control Ctl in Root.Controls)

{

Control FoundCtl = FindControlRecursive(Ctl, Id);

if (FoundCtl != null)

return FoundCtl;

}

return null;

}

Read More

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s