How do I loop through TextBoxes and clear them?

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?
 
L

lisa

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
 
M

Mythran

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
 
M

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
 
P

Paul D. Fox

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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top