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

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 in this case, start it by calling:

LoopTextBoxes(Me)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>