CheckBox in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the CheckBox control
Basically it's a box that the user can check and clear.
The CheckBox control provides a lots of events but the most used is certainly CheckChanged event that you could use to perform some action.
Same like a Button a CheckBox can display a textual caption, a picture, or both but unlike a RadioButton, each CheckBox choice is independent of all others CheckBox controls (if any).
Usually we use the CheckBox control's Checked property to tell if it is checked (returns True if the CheckBox is checked and False if it is not).
Ok let's see an example of CheckBox. For instance, let's upgrade our previous example making the exit application optional, but before that change it's Name peroperty to ExitOption, change Text to "Is Exit Allowed?" and then double click the control to generate the CheckedChanged event handler.
Private Sub ExitOption_CheckedChanged(sender As Object, e As EventArgs) _ Handles ExitOption.CheckedChanged End SubWe gonna use a CheckedChanged event, that fires whenever the control's value changes so based on this value we allow and disallow exiting the application as shown in the following code:
Private IsExitAllowed As Boolean ' a flag variable Private Sub ExitOption_CheckedChanged(sender As Object, e As EventArgs)_ Handles ExitOption.CheckedChanged If ExitOption.Checked = True Then IsExitAllowed = True ' you can close the app Else IsExitAllowed = False ' you cannot close the app End If End SubThen use the flag variable in the Button's click event to make the exit optional:
Private Sub ButtonExit_Click(sender As Object, e As EventArgs) _ Handles ButtonExit.Click If IsExitAllowed = True Then Application.Exit() Else MessageBox.Show("You are not allowed to exit the application.") End If End Sub
Note: If your form requires say five or more CheckBox controls with related purposes, you may want to consider using a CheckedListBox instead. Previous Lesson | Next Lesson