Hi,
Of late I have found this one question related to finding controls inside the page dynamically and apply some similar function to them. Like put a css class to all the textbox (or for that matter any control) in a page. Remember a page can have textbox as a control directly under it, or the textbox can be inside another composite control (like login control, gridview, detailview) inside the page.
Many a times we do not want to do this work for individual control but rather have a function, which will do this for all the control in the page. This way it becomes more maintainable and easy to implement.
To get this work done all we need is to make a function, which finds all the textbox (or for that matter any control) controls. The function needs to call itself if there are child controls in the control being parsed. Below is the code that I used to do the same.
public void findChildControl(Control ctrls)
{
foreach (Control ctrl in ctrls.Controls)
{
if (ctrl is TextBox)
{
// Do whaever You wnatwill textbox
}
else
{
// If the control has some child control look into those controls also
if (ctrl.Controls.Count > 0)
{
findChildControl(ctrl);
}
}
}
}
Now to find the control you need to call the function like this.
findChildControl(Page);
If you want to search only under a certain control then u can also pass the specific control like this.
findChildControl(gridview1);
To make the function more generic I polymerphised it and created a new one with different signatures. I changed it to take a type T which can be defined by the consumer of the function and based on that I will check for the control. So now the type of control (Textbox here) need not be hard coded in the function. Also I have added a new parameter to the function, which takes a delegate (function pointer) as an argument (The function pointer takes a control as an argument). Now the user can also pass back a function name that will be invoked by the function.
public delegate void processControl(Control ctr);
public void findChildControl<T>(Control ctrls , processControl pc) where T : System.Web.UI.Control
{
foreach (Control ctrl in ctrls.Controls)
{
if (ctrl is T)
{
pc.Invoke(ctrl);
}
else
{
// If the control has some child control look into those controls also
if (ctrl.Controls.Count > 0)
{
findChildControl<T>(ctrl, pc);
}
}
}
}
Before calling the function we make a function, which takes a parameter of type Control like this.
private void processControl1(Control ctrl)
{
Response.Write(ctrl.ID);
}
And we call the function like this.
findChildControl<TextBox>(Page, processControl1);
Vikram