Visual Basic .NET - Checkbox Control

The VB.NET CheckBox control is used to allow users to select one or more options from a set of choices. It is a user interface element that is typically used in forms or dialog boxes. Here are some of the basic properties, methods, and events of the CheckBox control:

Properties:

  • Checked: gets or sets a value indicating whether the control is checked.
  • Text: gets or sets the text associated with the control.
  • TextAlign: gets or sets the alignment of the text within the control.
  • Appearance: gets or sets the appearance of the control.

Events:

  • CheckedChanged: occurs when the Checked property of the control changes.
  • CheckStateChanged: occurs when the Checked or Indeterminate state of the control changes.

Example:

Assuming you have a form with a CheckBox control named CheckBox1, you can use the following code to detect whether the control has been checked:

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
    If CheckBox1.Checked Then
        MessageBox.Show("The checkbox is checked!")
    Else
        MessageBox.Show("The checkbox is unchecked!")
    End If
End Sub

This code sets up an event handler for the CheckedChanged event of the CheckBox control. When the Checked property of the control changes, the event handler displays a message box indicating whether the control is checked or unchecked.

Let's say we have a form with three CheckBox controls and a Button control. The CheckBox controls are named chkPizza, chkBurger, and chkFries. When the user checks one or more of these CheckBox controls and clicks the Button control, we want to display a message box with the items that the user has selected.

We can use the following code for the Button control's Click event:

Private Sub btnOrder_Click(sender As Object, e As EventArgs) Handles btnOrder.Click
    Dim selectedItems As String = ""
    If chkPizza.Checked Then
        selectedItems += "Pizza" & vbCrLf
    End If
    If chkBurger.Checked Then
        selectedItems += "Burger" & vbCrLf
    End If
    If chkFries.Checked Then
        selectedItems += "Fries" & vbCrLf
    End If
    If selectedItems = "" Then
        MessageBox.Show("Please select at least one item.")
    Else
        MessageBox.Show("You have ordered the following items: " & vbCrLf & selectedItems)
    End If
End Sub

In this code, we first declare a variable named selectedItems to store the selected items. Then, we use if statements to check if each CheckBox control is checked. If a CheckBox control is checked, we add its text to the selectedItems string variable.

After checking all three CheckBox controls, we check if selectedItems is empty. If it is, we display a message box asking the user to select at least one item. If selectedItems is not empty, we display a message box with the selected items. The vbCrLf constant is used to add a newline character to the selected items string for readability.