Loop Through All Controls on an ASP.net Webpage
If you're like me, you have on occasion had a need to loop through all the controls on your page. Sadly there is no simple ForEach loop that will take you through all the controls on the page (that would be just too easy). But there is a set hierarchy and by going through that hierarchy, you can get them all.
The basicic heirachy of controls on a page (which uses MasterPages) is MasterPage then HtmlForm then ContentPlaceHolder and then finally will come all the labels, textboxes, and whatever other controls you seek (note that if these controls contain children of their own, like a GridView, you will need to loop through that control to get all the included controls in it).
In order to loop through all of these and get to the controls you really care about, you need to first go through each collection of controls and then when you hit a control of the next type down in the hierarchy, loop through all controls in that particular control. The code below will do just this.
foreach (Control masterControl in Page.Controls)
{
if (masterControl is MasterPage)
{
foreach (Control formControl in masterControl.Controls)
{
if (formControl is System.Web.UI.HtmlControls.HtmlForm)
{
foreach (Control contentControl in formControl.Controls)
{
if (contentControl is ContentPlaceHolder)
{
foreach (Control childControl in contentControl.Controls)
{
}
}
}
}
}
}
}
If you want to get a specific control, for example you'd like to set all your labels to a new message, you simply need to check what type of control it is and if it happens to be a label control, cast a new label as that control and set your text. The following code will set all labels on your page to the text "You found me!". You will need to place this code in the inner most ForEach loop.
if (childControl is Label)
{
Label newLabel = (Label)childControl;
newLabel.Text = "You found me!"
}
Alternatively to this method, you could create a function that calls itself recursively and drills down through each control and their children. That would have advantages over the method described above as you would be guaranteed to hit all items on the page (as I mentioned earlier, this code won't get controls inside objects like GridViews). If that's not a requirement of yours though (or you fear recursion as many young programmers do), this method seems a bit easier to follow than recursive calls and won't unnecessarily go through controls you don't care about.
If you're looking for a client-side approach to accessing your controls, check out my article Enable/Disable All Buttons in a GridView using JavaScript, which could be easily modified to get not just all controls in a GridView but all controls on the page.
-->
This article has been view 23662 times.
|