February 18, 2019
Hot Topics:

Even More Windows Secrets for Visual Basic .NET

  • February 10, 2003
  • By Karl Moore
  • Send Email »
  • More Articles »

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 _
      If TypeOf (objControl) Is _
                          System.Windows.Forms.TextBox Then
        objControl.Text = ""  ' Clear TextBox
      ElseIf _
         TypeOf (objControl) Is System.Windows.Forms.CheckBox _
        Dim objCheckBox As System.Windows.Forms.CheckBox _
            = objControl
        objCheckBox.Checked = False ' Uncheck CheckBox
      ElseIf _
         TypeOf (objControl) Is System.Windows.Forms.ComboBox _
        Dim objComboBox As System.Windows.Forms.ComboBox _
            = objControl
        objComboBox.SelectedIndex _
           = -1 ' Deselect any ComboBox entry
      End If
    End If
End Sub

You could use this function behind your form, as so:


Page 2 of 5

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date