Navigation

Search

Categories

On this page

Loop through all or certain type of controls on the ASP.NET Page

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Wednesday, December 12, 2007
Wednesday, December 12, 2007 1:34:49 PM (Eastern Standard Time, UTC-05:00) ( )


You can loop through all or certain type of controls on ASP.NET Page using this code. Code will loop through also those controls that are contained in some other container that Form, Panel for example. Example of looping through all TextBoxes on Page.

[C#]
private void LoopTextBoxes (Control parent) 
        {
            foreach (Control c in parent.Controls) 
            {
                TextBox tb = c as TextBox;
                if (tb != null)
                    //Do something with the TextBox

                if (c.HasControls())
                    LoopTextBoxes(c);
            }
        }

And you can start the looping by calling: 
LoopTextBoxes(Page);
[VB]
  Private Sub LoopTextBoxes(ByVal parent As Control)
        Dim c As Control
        For Each c In parent.Controls
            If c.GetType() Is GetType(TextBox) Then
                'Do something with the TextBox
            End If

            If c.HasControls Then
                LoopTextBoxes(c)
            End If
        Next
    End Sub
And you can start the looping by calling:
LoopTextBoxes(Me)