PDA

Click to See Complete Forum and Search --> : Looping through controls (vb.net)


wild_bill
Apr 26th, 2005, 12:26 PM
I'm new to ASP.NET. I've been asked to convert one of my windows apps into an asp page. I would like to loop through the controls on my page, so I thought using a similar syntax would work, but it doesnt. Here is an example of the code I'm trying to use:


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each oControl As Control In Page.Controls
If TypeOf oControl Is TextBox Then
Dim txtbox As TextBox = CType(oControl, TextBox)
txtbox.Text = Date.Now.ToString
End If
Next
End Sub

wild_bill
Apr 26th, 2005, 01:21 PM
I got it working with:


Private Sub setdatetime(ByVal gui As Control)
For Each ocontrol As Control In Page.Controls
If TypeOf ocontrol Is TextBox Then
Dim txtbox As TextBox = CType(ocontrol, TextBox)
txtbox.Text = Date.Now.ToString
Else
setdatetime(ocontrol)
End If
Next
End Sub


I wrote all the controls that aren't textboxes out to a variable. Form1 showed up as a control, but I can't loop through Form1.Controls, as it hasn't been declared. Any ideas how to declare Form1, so I don't have to recursivly search through all the controls?

nemaroller
Apr 26th, 2005, 04:19 PM
You can simply put this at the top of your code-behind:

Protected Form1 As System.Web.UI.HtmlControls.HtmlForm

then use:

For Each ocontrol As Control In Form1.Controls

Magiaus
Apr 26th, 2005, 07:43 PM
Yeah, that little Page.Form.Controls thing is annoying....