Even More Windows Secrets for Visual Basic .NET, Page 2
How to 'Reset' a Form
If you've created a data entry style Windows form that needs "resetting" with each addition, the code to clear the TextBox controls, uncheck the CheckBox controls, and so on can all get a little repetitive—particularly if you have to write it for multiple forms.
That's where the following method could prove useful. Simply pass in a form as a parameter, and it'll reset the main data entry controls: TextBox, CheckBox, and ComboBox. You also could easily extend it to cater to RadioButton, ListBox, CheckedListBox, DomainUpDown, NumericUpDown, MonthCalendar, and DateTimePicker controls, too. To ensure flexibility, this subroutine automatically bypasses all controls with "skip" somewhere in the Tag property.
Here's the code:
Public Sub ResetForm(ByVal FormToReset As Form)
' Resets the main data entry controls
' on the passed FormToReset
Dim objControl As Control
' Loop round every control on the form
For Each objControl In FormToReset.Controls
' Check we don't need to skip this control
If InStr(objControl.Tag, "skip", CompareMethod.Text) = 0 _
Then
If TypeOf (objControl) Is _
System.Windows.Forms.TextBox Then
objControl.Text = "" ' Clear TextBox
ElseIf _
TypeOf (objControl) Is System.Windows.Forms.CheckBox _
Then
Dim objCheckBox As System.Windows.Forms.CheckBox _
= objControl
objCheckBox.Checked = False ' Uncheck CheckBox
ElseIf _
TypeOf (objControl) Is System.Windows.Forms.ComboBox _
Then
Dim objComboBox As System.Windows.Forms.ComboBox _
= objControl
objComboBox.SelectedIndex _
= -1 ' Deselect any ComboBox entry
End If
End If
Next
End Sub
You could use this function behind your form, as so:
ResetForm(Me)
