Friday, December 31, 2010

Finds a Control recursively in Asp.net

On one of my project i need to Find the controls till get the result control so i have built the code like this...

Below is Method Definition :

/// <summary>
/// Finds a Control recursively. Note finds the first match and exists
/// </summary>
/// <param name="ContainerCtl"></param>
/// <param name="IdToFind"></param>
/// <returns></returns>
public static Control FindControlRecursive(Control Root, string Id)
{
string str =string.Empty;
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
{
switch (Id)
{
case "hdnProductId":
staticProductId = ((System.Web.UI.HtmlControls.HtmlInputHidden)FoundCtl).Value;
break;
case "hdnProductName":
staticProductName = ((System.Web.UI.HtmlControls.HtmlInputHidden)FoundCtl).Value;
break;
}
break;
}
}
return null;
}

Below is Method Definition in GIF Format :


Below is how to call that method:-

FindControlRecursive(this.Page.Master, "hdnProductId");
FindControlRecursive(this.Page.Master, "hdnProductName");

Below is how to call that method in Gif Format:-

No comments:

Post a Comment