Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Clear all textboxes/dropdown lists on page

ASP.NET 101

Clear all textboxes/dropdown lists on page

by  PsychoCoder  Posted    (Edited  )
When I started working with .Net I looked and looked to find a way to clear all elements on a page without having to go:

textbox1.text = string.empty
textbox2.text = string.empty
........

and so on, so I wrote this little sub procedure to accomplish this and I'm sharing it with other developers in hopes it might save someone else the time it took me to find a solution for this problem:.

What this does it it runs through the first "container" (a table is a container, the page is a container, etc) and empties the textboxes and selected values of all dropdown lists, then it calls itself until all containers have been cleared. You can leave the ByVal tb As TextBox off if you like, I had it so I could set the focus to a certain textbox when the sub was complete.


Code:
Public Shared Sub EmptyTextBoxes(ByVal parent As Control,[b]ByVal tb As TextBox[/b]) 
	For Each c As Control In parent.Controls 'LOOP THROUGHN ALL CONTROLS 
		If c.GetType() Is GetType(TextBox) Then 'IF ITS A TEXTBOX THEN EMPTY IT 
			CType(c, TextBox).Text = String.Empty 
			tb.Focus()
		ElseIf c.GetType Is GetType(DropDownList) Then 'ELSE IF ITS A DROPDOWN LIST SET SELECTED VALUE TO -1     
			CType(c, DropDownList).SelectedIndex = 0 
		End If 
		If c.HasControls Then 'CALL ITSELF (GET ALL OTHER ELEMENTS IN OTHER CONTAINERS) 
			EmptyTextBoxes(c) 
		End If 
	Next 
End Sub

I have this Sub in a class file (ReportTemplate.vb) but you can also use it in the code behind file (.aspx.vb). To call it do as follows (this is how I call it in my application from the class file), always use Me as the control (first parameter) to start the Sub on the page level:

Code:
ReportTemplate.EmptyTextBoxes(Me, *textbox name*)

It comes in very hand at the end of Subs or Functions you use to enter data into a database (then you can clear the form at the end of the Sub) or for a Clear button on a form.

On a side note for all those C# developers I also converted this Sub to C#:

Code:
public static void EmptyTextBoxes(Control parent, TextBox tb) 
{ 
 foreach (Control c in parent.Controls) { 
   if (c.GetType() == typeof(TextBox)) { 
     ((TextBox)(c)).Text = string.Empty; 
     tb.Focus(); 
   } else if (c.GetType == typeof(DropDownList)) { 
     ((DropDownList)(c)).SelectedIndex = 0; 
   } 
   if (c.HasControls) { 
     EmptyTextBoxes(c, tb); 
   } 
 } 
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top