Loop thru controls on a html form

Loop thru controls on a html form

Post by Michael Be » Thu, 18 Nov 2004 12:26:55


I am new to .net programming and I want to know if I can loop thru a
specified number of controls on an html form.

In Access, the code looks like this:
For i = 1 to 10
Me("txtAlternate" & i) = ""
Next i

Is there an equivalent code in asp.net?

TIA
Mike
 
 
 

Loop thru controls on a html form

Post by Derek Harm » Thu, 18 Nov 2004 14:42:31


' Someplace within the WebForm1 class, most likely in Page_Load.
'
Dim c As System.Web.UI.Control
For Each c In Me.Controls
' Do something with c
Next c

This will go through all of the top level controls on the web form,
but not nested controls (each c will have it's own Controls collection
containing it's children, so you can choose to descend recursively if
you so choose).

Public Sub DescendThroughControls( ByVal controlSet As System.Web.UI.ControlCollection )
Dim c As System.Web.UI.Control

For Each c In controlSet
' Do something with c.
If ( c.Controls.Count > 0 ) Then
' This step will do something with c's child controls.
DescendThroughControls( c.Controls )
End If
Next c

End Sub
' . . .
' called with the following statement in Page_Load
' . . .
Me.DescendThroughControls( Me.Controls)

Finally, if you're looking for a Control on the Page with a specific ID then you
can use Me.FindControl( name ) to return an instance of that Control to do
something with. Again, it only works within your immediate ControlCollection
so you may need to descend into the child control collections.


Derek Harmon

 
 
 

Loop thru controls on a html form

Post by Cor Ligthe » Thu, 18 Nov 2004 17:34:23

Michael,

The format from Derek did never works for me direct on a webpage, however
because his convincing way of writting I am not sure, however when it does
not go you can try this on.

\\\\
Dim frm As Control = Me.FindControl("Form1")
Dim ctl As Control
For Each ctl In frm.Controls
Dim tb As TextBox
If TypeOf ctl Is TextBox Then
tb = DirectCast(ctl, TextBox)
tb.Text = String.Empty
End If
Next
///

I hope this helps?

Cor