Iterate through textboxes in VB Web App

There’s a few answers to this sort of question, but none of them seem very clear to me and I have no experience with JQuery, so I’m asking here.

I have a VB Web Application with a bunch of textboxes on it in Default.aspx (Using the basic template in Visual Web Designer 2010 Express). I’d like to iterate through those textboxes using some sort of VB solution if at all possible and clear them when the user presses a button. I’ve tried using something like this:

Dim cControl As Control
For Each cControl in Me.Controls
    If cControl Is TextBox Then
        cControl.Text = ""
    EndIf
Next

But this doesn’t work. If anyone could point me in the right direction, that would be great. Thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are 2 problems with your code. First, using the code:

For Each cControl in Me.Controls
  ...
Next

will only work if all of the textboxes are on the main page, and not on a panel, in a group box, etc.

Second, the code

If cControl is Textbox Then

will fail because cControl is not the exact same object as Textbox. You want to be checking to see if the Type of cControl is Textbox. A recursive solution to your code would be:

Public Sub ClearTextBoxes (ctrl as Control)
  If Ctrl.HasChildren Then
    For each childCtrl as Control in Ctrl.Controls
      ClearTextBoxes(childCtrl)
    Next
  Else
    If TypeOf Ctrl is TextBox Then
      DirectCast(Ctrl, TextBox).Text = String.Empty
    End If
  End If
End Sub

To run the method, you would then call:

ClearTextBoxes(Me)

Method 2

Unless you have the textboxes nested in some sort of container control, this should work…

    Dim cControl As Control
    For Each cControl In Page.Form.Controls
        If cControl.GetType().ToString() = "System.Web.UI.WebControls.TextBox" Then
            CType(cControl, TextBox).Text = ""
        End If
    Next

Method 3

You need to loop through recursively, because some controls are probably nested in other controls, like Panels, etc.

public void ClearTextBoxes(Control ctrl)
{
    foreach (Control childCtrl in ctrl.Controls)
    {
        if (childCtrl is TextBox)
        {
             ((TextBox)ctrl).Text = String.Empty;
        }

        ClearTextBoxes(childCtrl);
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x