How do I loop through TextBoxes and clear them?

  • Thread starter Thread starter Paul D. Fox
  • Start date Start date
P

Paul D. Fox

I want to be able to loop through all the TextBoxes on a page and clear
their values. How can I write a function to do that?
 
Paul said:
I want to be able to loop through all the TextBoxes on a page and clear
their values. How can I write a function to do that?

For Each myControl As Control In Page.Controls
If TypeOf myControl Is TextBox Then
CType(myControl, TextBox).Text = String.Empty '(or "")
End If
Next myControl

Lisa
 
Paul D. Fox said:
I want to be able to loop through all the TextBoxes on a page and clear
their values. How can I write a function to do that?

C#:

public void ClearTextBoxes(WebControl Parent)
{
foreach (WebControl child in Parent.Controls) {
if (typeof(child) is TextBox) {
((TextBox) child).Text = String.Empty;
} else if (typeof(child) is IContainer) {
ClearTextBoxes(child);
}
}
}

VB.Net:

Public Sub ClearTextBoxes(ByVal Parent As WebControl)
For Each child As WebControl In Parent.Controls
If GetType(child) Is TextBox
DirectCast(child, TextBox).Text = String.Empty
ElseIf GetType(child) Is IContainer
ClearTextBoxes(child)
End If
Next
End Sub


Off the top of my head....also, I believe it's IContainer that the second if
needs to check. If not, it needs to be the interface that exposes the
"Controls" collection.

HTH,
Mythran
 
For Each myControl As Control In Page.Controls
If TypeOf myControl Is TextBox Then
CType(myControl, TextBox).Text = String.Empty '(or "")
End If
Next myControl

Lisa

AFAIK, if there is an IContainer in the Controls collection and it has
Controls on it, the Controls property of the object implementing IContainer
will contain controls not found in the Controls collection of the Page.

Mythran
 
Sorry folks, but none of these methods seem to be working. This is a web
form and after running the routine, the values are stil there. I've even
set EnableViewState="False".

Paul
 
you actually need to use your form name as the collections object. I had a
lot of trouble with this until I found:

http://www.code101.com/Code101/DisplayArticle.aspx?cid=83

I did the following which works well:

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

....

For Each myControl As Control In Form1.Controls
If TypeOf myControl Is TextBox Then
CType(myControl, TextBox).Text = ""
End If
Next myControl
 
Back
Top