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!
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)
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
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);
}
}