Results 1 to 4 of 4

Thread: Looping through controls (vb.net)

  1. #1

    Thread Starter
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,993

    Looping through controls (vb.net)

    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:

    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         For Each oControl As Control In Page.Controls
    3.             If TypeOf oControl Is TextBox Then
    4.                 Dim txtbox As TextBox = CType(oControl, TextBox)
    5.                 txtbox.Text = Date.Now.ToString
    6.             End If
    7.         Next
    8.     End Sub

  2. #2

    Thread Starter
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,993

    Re: Looping through controls (vb.net)

    I got it working with:

    VB Code:
    1. Private Sub setdatetime(ByVal gui As Control)
    2.         For Each ocontrol As Control In Page.Controls
    3.             If TypeOf ocontrol Is TextBox Then
    4.                 Dim txtbox As TextBox = CType(ocontrol, TextBox)
    5.                 txtbox.Text = Date.Now.ToString
    6.             Else
    7.                 setdatetime(ocontrol)
    8.             End If
    9.         Next
    10.     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?

  3. #3
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: Looping through controls (vb.net)

    You can simply put this at the top of your code-behind:
    VB Code:
    1. Protected Form1 As System.Web.UI.HtmlControls.HtmlForm

    then use:
    VB Code:
    1. For Each ocontrol As Control In Form1.Controls

  4. #4
    Frenzied Member Magiaus's Avatar
    Join Date
    Mar 2002
    Location
    swamp land
    Posts
    1,267

    Re: Looping through controls (vb.net)

    Yeah, that little Page.Form.Controls thing is annoying....
    Magiaus

    If I helped give me some points.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width