Monday, January 11, 2010

Loop through controls when using masterpage

The basic hierarchy 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.

Ref: http://www.krissteele.net/blogdetails.aspx?id=104

No comments: