Free Information Technology Magazines and eBooks

Tuesday, April 14, 2009

VB.NET Trick: Clear all textboxes on a form

One of the most common function we need in a VB form is clearing textbox controls. We usually see it on add or cancel button of a maintenance form. Beginners often code it this way:


txtCategoryID.Text = ""
txtCategoryName.Text = ""


This style of coding is good only for less than five (5) textboxes. More than that will make the code longer and less organize. One technique we can apply is to use the Controls collection, so the previous will now look like this:


Private Sub ClearTextboxes()
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = ""
End If
Next
End Sub


You can also use the same technique on other type of controls and other properties of a control. Below is a sample code to disable or enable all textboxes on a form.


Private Sub EnableTextboxes(ByVal IsEnable As Boolean)
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Enabled = IsEnable
End If
Next
End Sub




1 comments:

omda_engineer2012 said...

Thanks very much , I'm so grateful