Clear a form's Controls?

M

Mark A. Deal

Can anybody tell me how to iterate through the controls on a form and clear
the textbox controls?

I've tried:
Dim objControl As Control

For Each objControl In Me.Controls

If TypeOf objControl Is TextBox Then

TextBox.Text = ""

End If

Next

Obviously does not work. Anybody?
--
Mark A. Deal
Document & Data Solutions, LLC
http://www.docsol.com
Time Matters AIC
HotDocs Certified Consultant
GhostFill Certified Consultant
 
K

Ken Cox [Microsoft MVP]

Hi Mark,

You're pretty close. Make sure you are getting to the Form controls, not
just the Page controls

Here's a sample:

Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
TextBox1.Text = "Textbox1"
TextBox2.Text = "Textbox2"
TextBox3.Text = "Textbox3"
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' Clears the text out of textboxes
' Jan 3/05 by Ken Cox - Microsoft MVP [ASP.NET]
Dim objTester As Control
Dim txtbx As TextBox
Dim frm As Control
' Get a reference to the form
frm = Page.FindControl("Form1")
' Make sure the form exists
If Not IsNothing(frm) Then
' Loop through all of the controls in the form
For Each objTester In frm.Controls
' Test this control to see if it is
' a textbox
If TypeOf (objTester) Is TextBox Then
' Assign the control to the textbox variable
txtbx = objTester
' Remove the text
txtbx.Text = ""
End If
' Go back for more, if any
Next
End If
End Sub

<form id="Form1" method="post" runat="server">
<p>
<asp:textbox id="TextBox1" runat="server"></asp:textbox></p>
<p>
<asp:textbox id="TextBox2" runat="server"></asp:textbox></p>
<p>
<asp:textbox id="TextBox3" runat="server"></asp:textbox></p>
<p>
<asp:button id="Button1" runat="server"
Text="Clear"></asp:button></p>
</form>

Does this help?

Ken
Microsoft MVP [ASP.NET]
Toronto
 

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,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top