Lesson 21 · CheckBox Control

The CheckBox Control

Master VB 2026's CheckBox — the Checked property, CheckedChanged events, groups of checkboxes for multi-select, three-state mode, iterating controls at runtime, and binding checkbox state to application logic.

Key Takeaway: A CheckBox lets the user toggle an option independently of all others — unlike RadioButtons, multiple checkboxes in the same container can all be checked at once. Read the state with chk.Checked (True/False) or chk.CheckState (Checked/Unchecked/Indeterminate). React to user changes with the CheckedChanged event. When you have many checkboxes, loop through the form's Controls collection and cast each to CheckBox rather than hard-coding every control name.
Checked
Boolean
True if ticked, False if not. Most-used property.
CheckState
CheckState enum
Checked / Unchecked / Indeterminate (three-state).
ThreeState
Boolean
Enable the indeterminate (greyed-out) middle state.
Text
String
Label shown to the right of the box.
CheckAlign
ContentAlignment
Position of the box (default MiddleLeft).
AutoCheck
Boolean
When True (default) clicking toggles Checked automatically.
Appearance
Appearance enum
Normal (box) or Button (looks like a toggle button).
FlatStyle
FlatStyle enum
Flat / Popup / Standard / System visual style.

21.1 Checked Property and CheckedChanged Event

The Checked property is the heart of a CheckBox. Read it in code to act on the user's selection, or set it to pre-tick a box when a form loads. The CheckedChanged event fires every time the value toggles — it is the right place to react immediately rather than waiting for a button click.

Basics.vb — Visual Basic 2026
' --- Reading Checked in a Button click ---
Private Sub btnOrder_Click(...) Handles btnOrder.Click
    Dim msg = ""
    If chkExtraShot.Checked  Then msg &= "Extra shot, "
    If chkOatMilk.Checked    Then msg &= "Oat milk, "
    If chkDecaf.Checked      Then msg &= "Decaf, "
    If msg = "" Then msg = "Standard espresso"
    lblOrder.Text = msg.TrimEnd(","c, " "c)
End Sub

' --- Setting Checked in code ---
Private Sub Form1_Load(...) Handles MyBase.Load
    chkNewsletter.Checked = True   ' pre-tick on startup
    chkTerms.Checked      = False  ' must be ticked by user
End Sub

' --- Reacting immediately with CheckedChanged ---
Private Sub chkDarkMode_CheckedChanged(...) Handles chkDarkMode.CheckedChanged
    If chkDarkMode.Checked Then
        Me.BackColor = Color.FromArgb(30, 30, 30)
        lblStatus.Text = "Dark mode ON"
    Else
        Me.BackColor = SystemColors.Control
        lblStatus.Text = "Dark mode OFF"
    End If
End Sub

' --- Toggling with Not ---
chkRememberMe.Checked = Not chkRememberMe.Checked   ' flip state in code

' --- Using If/Else vs IIf for short assignments ---
Dim fee = If(chkExpressShipping.Checked, 15.0, 0.0)
lblShipping.Text = fee.ToString("C2")
CheckBox vs RadioButton

Use a CheckBox when options are independent — the user can select any combination (or none). Use a RadioButton (Lesson 22) when exactly one option must be selected from a mutually exclusive group. A classic rule: toppings on a pizza = checkboxes; pizza size = radio buttons.

Try It — Simulation 21.1: Coffee Order Builder

Tick any combination of extras. The order summary and price update in real time using CheckedChanged-style logic. The VB code trace shows exactly which Checked reads are happening.

Coffee Order Builder — Form1.vb
Select extras:
Extras (CheckBox group — any combination allowed)
Extra shot (+RM 2.00)
Oat milk (+RM 1.50)
Decaf (+RM 0.00)
Whipped cream (+RM 1.00)
Vanilla syrup (+RM 0.80)

21.2 Groups of CheckBoxes — Looping Through Controls

When a form has many checkboxes, hard-coding each one's name into an If chain becomes tedious and error-prone. The better approach is to loop through the form's Controls collection (or a panel's), use TypeOf ... Is CheckBox to filter, and cast with DirectCast.

Groups.vb — Visual Basic 2026
' --- Loop through all CheckBoxes on a Panel ---
Private Function GetCheckedItems(panel As Panel) As List(Of String)
    Dim result As New List(Of String)
    For Each ctrl As Control In panel.Controls
        If TypeOf ctrl Is CheckBox Then
            Dim chk = DirectCast(ctrl, CheckBox)
            If chk.Checked Then result.Add(chk.Text)
        End If
    Next
    Return result
End Function

' --- Select All / Clear All helpers ---
Private Sub SetAllCheckBoxes(panel As Panel, state As Boolean)
    For Each ctrl As Control In panel.Controls
        If TypeOf ctrl Is CheckBox Then
            DirectCast(ctrl, CheckBox).Checked = state
        End If
    Next
End Sub

Private Sub btnSelectAll_Click(...) Handles btnSelectAll.Click
    SetAllCheckBoxes(pnlOptions, True)
End Sub

Private Sub btnClearAll_Click(...) Handles btnClearAll.Click
    SetAllCheckBoxes(pnlOptions, False)
End Sub

' --- Count how many are checked ---
Private Function CountChecked(panel As Panel) As Integer
    Return panel.Controls.OfType(Of CheckBox)().Count(Function(c) c.Checked)
End Function

' --- Validate: at least one must be checked ---
Private Function ValidateAtLeastOne(panel As Panel) As Boolean
    If CountChecked(panel) = 0 Then
        MessageBox.Show("Please select at least one option.", "Validation",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Return False
    End If
    Return True
End Function

' --- Persist state to settings (save/load ticked boxes) ---
Private Sub SaveCheckBoxStates()
    My.Settings.ShowNews      = chkNews.Checked
    My.Settings.ShowAds       = chkAds.Checked
    My.Settings.ShowAnalytics = chkAnalytics.Checked
    My.Settings.Save()
End Sub
Try It — Simulation 21.2: Newsletter Preferences

Demonstrates looping through a group of checkboxes with Select All / Clear All buttons. The count and selected list update instantly, just as Controls.OfType(Of CheckBox)() would work at runtime.

Newsletter Preferences
Email notifications:
Select any topics (multiple allowed)
Topics Panel — pnlTopics.Controls
Breaking News
Technology
Business & Finance
Sports
Health & Wellness
Entertainment

21.3 Three-State CheckBoxes

Setting ThreeState = True enables a third visual state — Indeterminate (a greyed-out box) — in addition to Checked and Unchecked. This is used when an option applies to some (but not all) of a selection, most famously in "Select All" parent checkboxes that control a list of child checkboxes.

ThreeState.vb — Visual Basic 2026
' --- ThreeState property enables Indeterminate state ---
' CheckState enum values: Checked, Unchecked, Indeterminate

Private Sub chkSelectAll_CheckedChanged(...) Handles chkSelectAll.CheckedChanged
    ' Ignore the Indeterminate state when the user clicks chkSelectAll
    If chkSelectAll.CheckState = CheckState.Indeterminate Then Return

    Dim state = chkSelectAll.Checked
    chkItem1.Checked = state
    chkItem2.Checked = state
    chkItem3.Checked = state
    chkItem4.Checked = state
End Sub

' --- Each child updates the parent "Select All" state ---
Private Sub AnyChild_CheckedChanged(...) Handles
        chkItem1.CheckedChanged, chkItem2.CheckedChanged,
        chkItem3.CheckedChanged, chkItem4.CheckedChanged

    Dim checkedCount = {chkItem1, chkItem2, chkItem3, chkItem4}.Count(
                            Function(c) c.Checked)
    Dim total        = 4

    ' Suppress re-entry while we update the parent
    RemoveHandler chkSelectAll.CheckedChanged, AddressOf chkSelectAll_CheckedChanged

    chkSelectAll.CheckState = If(checkedCount = 0,   CheckState.Unchecked,
                               If(checkedCount = total, CheckState.Checked,
                                                         CheckState.Indeterminate))
    AddHandler chkSelectAll.CheckedChanged, AddressOf chkSelectAll_CheckedChanged
End Sub

' --- Reading CheckState ---
Select Case chkOption.CheckState
    Case CheckState.Checked       : lblStatus.Text = "Yes"
    Case CheckState.Unchecked     : lblStatus.Text = "No"
    Case CheckState.Indeterminate : lblStatus.Text = "Some"
End Select
Try It — Simulation 21.3: Three-State Select All

The parent "Select All" checkbox shows Checked (all ticked), Indeterminate (some ticked), or Unchecked (none ticked). Clicking the parent toggles all children. Clicking individual children updates the parent state automatically.

File Backup Selector — Three-State Demo
chkSelectAll (ThreeState = True)
Select All Files
Documents (2.4 GB)
Pictures (8.1 GB)
Videos (42.6 GB)
Music (3.8 GB)
Downloads (1.2 GB)

21.4 Appearance = Button — Toggle Buttons

Setting Appearance = Appearance.Button makes a CheckBox look like a push button. When clicked it stays "pressed" (checked) until clicked again. This is perfect for toolbar toggles (Bold / Italic), mode switches, and filter toggles where the pressed visual state conveys the active mode clearly.

ToggleButton.vb — Visual Basic 2026
' In the Designer, set Appearance = Button and FlatStyle = Flat
' The checkbox behaves identically — only the look changes.

Private Sub chkBold_CheckedChanged(...) Handles chkBold.CheckedChanged
    Dim style = txtEditor.Font.Style
    If chkBold.Checked Then
        txtEditor.Font = New Font(txtEditor.Font, style Or FontStyle.Bold)
    Else
        txtEditor.Font = New Font(txtEditor.Font, style And Not FontStyle.Bold)
    End If
End Sub

Private Sub chkItalic_CheckedChanged(...) Handles chkItalic.CheckedChanged
    Dim style = txtEditor.Font.Style
    txtEditor.Font = New Font(txtEditor.Font,
        If(chkItalic.Checked, style Or FontStyle.Italic,
                               style And Not FontStyle.Italic))
End Sub

' Toggle panel visibility — common UI pattern
Private Sub chkShowFilters_CheckedChanged(...) Handles chkShowFilters.CheckedChanged
    pnlFilters.Visible = chkShowFilters.Checked
    chkShowFilters.Text = If(chkShowFilters.Checked, "Hide Filters ▲", "Show Filters ▼")
End Sub
Try It — Simulation 21.4: Text Editor Toolbar

Toggle-button style checkboxes controlling text formatting. Each button stays visually pressed when active, just like Appearance = Button with FlatStyle = Flat. Mix any combination of Bold, Italic, Underline, and colour.

Mini Text Editor — Appearance=Button CheckBoxes
Type here and use the toolbar to style your text.

21.5 Practical: Application Settings Form

SettingsForm.vb — Visual Basic 2026
' Real-world settings form pattern:
' 1. Load saved settings into checkboxes on Form_Load
' 2. Enable/disable dependent controls based on Checked state
' 3. Save back when OK is clicked

Private Sub SettingsForm_Load(...) Handles MyBase.Load
    ' Restore from app settings
    chkAutoSave.Checked        = My.Settings.AutoSave
    chkAutoSaveInterval.Enabled = chkAutoSave.Checked
    nudInterval.Enabled         = chkAutoSave.Checked

    chkNotifications.Checked   = My.Settings.Notifications
    chkSoundAlerts.Enabled      = chkNotifications.Checked
    chkPopupAlerts.Enabled      = chkNotifications.Checked

    chkStartWithWindows.Checked = My.Settings.StartWithWindows
    chkMinimizeToTray.Checked   = My.Settings.MinimizeToTray
End Sub

' Enable/disable sub-options based on parent checkbox
Private Sub chkAutoSave_CheckedChanged(...) Handles chkAutoSave.CheckedChanged
    chkAutoSaveInterval.Enabled = chkAutoSave.Checked
    nudInterval.Enabled          = chkAutoSave.Checked
End Sub

Private Sub chkNotifications_CheckedChanged(...) Handles chkNotifications.CheckedChanged
    chkSoundAlerts.Enabled = chkNotifications.Checked
    chkPopupAlerts.Enabled = chkNotifications.Checked
    If Not chkNotifications.Checked Then
        chkSoundAlerts.Checked = False
        chkPopupAlerts.Checked = False
    End If
End Sub

' Save on OK
Private Sub btnOK_Click(...) Handles btnOK.Click
    My.Settings.AutoSave          = chkAutoSave.Checked
    My.Settings.Notifications     = chkNotifications.Checked
    My.Settings.SoundAlerts       = chkSoundAlerts.Checked
    My.Settings.PopupAlerts       = chkPopupAlerts.Checked
    My.Settings.StartWithWindows  = chkStartWithWindows.Checked
    My.Settings.MinimizeToTray    = chkMinimizeToTray.Checked
    My.Settings.Save()
    Me.DialogResult = DialogResult.OK
    Me.Close()
End Sub
Try It — Simulation 21.5: Application Settings

Demonstrates parent–child enabling: ticking "Auto Save" enables its sub-options; unticking disables and resets them. Ticking "Notifications" enables sound and popup sub-options. The VB code trace shows which .Enabled assignments occur on each CheckedChanged.

Application Settings
Saving
Auto-save every
Create backup copy
Sync to cloud
Notifications
Enable notifications
Sound alerts
Popup alerts
Startup
Start with Windows
Minimize to system tray

21.6 GitHub Copilot — CheckBox Patterns

GitHub Copilot — Permission Matrix
You typed: ' Build a user permission matrix: rows = users, columns = permissions (Read, Write, Delete, Admin). Use CheckBoxes created at runtime in a TableLayoutPanel. Generate a summary when the OK button is clicked.'
' Runtime CheckBox grid for permission matrix.
Private _perms() As String = {"Read", "Write", "Delete", "Admin"}
Private _users() As String = {"Alice", "Bob", "Charlie"}

Private Sub BuildPermissionGrid()
    tlpMatrix.RowCount    = _users.Length + 1
    tlpMatrix.ColumnCount = _perms.Length + 1
    tlpMatrix.Controls.Clear()

    ' Header row
    For c = 0 To _perms.Length - 1
        tlpMatrix.Controls.Add(New Label With {.Text = _perms(c), .Font = New Font("Segoe UI", 9, FontStyle.Bold)},
                               c + 1, 0)
    Next

    ' Data rows
    For r = 0 To _users.Length - 1
        tlpMatrix.Controls.Add(New Label With {.Text = _users(r)}, 0, r + 1)
        For c = 0 To _perms.Length - 1
            Dim chk As New CheckBox With {
                .Name = $"chk_{_users(r)}_{_perms(c)}",
                .Checked = (c = 0)  ' everyone gets Read by default
            }
            tlpMatrix.Controls.Add(chk, c + 1, r + 1)
        Next
    Next
End Sub

Private Sub btnOK_Click(...) Handles btnOK.Click
    Dim sb As New Text.StringBuilder
    For r = 0 To _users.Length - 1
        Dim granted = _perms.Where(Function(p)
            Dim key = $"chk_{_users(r)}_{p}"
            Dim chk = DirectCast(tlpMatrix.Controls(key), CheckBox)
            Return chk.Checked
        End Function)
        sb.AppendLine($"{_users(r)}: {String.Join(", ", granted)}")
    Next
    MessageBox.Show(sb.ToString(), "Permissions")
End Sub
Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while working with CheckBoxes:

  • "Write a Sub that reads all checked CheckBoxes inside a GroupBox, builds a comma-separated summary string, and displays it in a Label"
  • "Create a 'Select All' CheckBox with ThreeState=True that controls 6 child CheckBoxes, using RemoveHandler/AddHandler to avoid recursive events"
  • "Implement a pizza order form with CheckBoxes for toppings (each with a price), a Label that shows the running total formatted with C2, and validation that at least one topping is selected"
  • "Show how to serialize checked CheckBox states to a JSON string using System.Text.Json and deserialize them back on Form_Load"

Lesson Summary

  • chk.Checked is a Boolean — True when ticked. Read it in a button click, or in the CheckedChanged event for immediate response. Set it in code to pre-configure a form on load.
  • Unlike RadioButtons, multiple CheckBoxes in the same container are independent — any combination can be selected simultaneously.
  • When you have many checkboxes, loop with For Each ctrl As Control In panel.Controls and TypeOf ctrl Is CheckBox rather than hard-coding every control name. Use LINQ: panel.Controls.OfType(Of CheckBox)() for concise iteration.
  • Three-state mode (ThreeState = True, CheckState property): use the Indeterminate state for "Select All" parents. Use RemoveHandler / AddHandler to prevent recursive CheckedChanged events when updating the parent from child handlers.
  • Appearance = Appearance.Button turns a CheckBox into a visually persistent toggle button — ideal for toolbars (Bold/Italic), mode switches, and filter toggles. The underlying Checked logic is identical.
  • Enable / disable child controls in the parent's CheckedChanged: set subControl.Enabled = parentChk.Checked. When unchecking a parent, also uncheck and disable its children to keep UI state consistent.

Exercises

Exercise 21.1 — Pizza Order Form

  • Create 8 CheckBoxes for toppings (pepperoni, mushroom, olives, etc.) each with a price
  • Show a running total Label that updates on every CheckedChanged event using a shared handler
  • Add a base price (small/medium/large via RadioButtons — Lesson 22) and format total with C2
  • Validate on Order button: at least one topping must be selected
  • Copilot challenge: Ask Copilot to "add a 'Recommended' button that pre-ticks the three most popular toppings using their .Checked properties"

Exercise 21.2 — File Filter Selector

  • Build a form with a "Select All" parent CheckBox (ThreeState = True) and 6 file-type children (.docx, .xlsx, .pdf, .jpg, .mp4, .zip)
  • Implement the full three-state parent ↔ child sync using RemoveHandler/AddHandler
  • Show count: "3 of 6 types selected" updating in real time
  • Add Select All / Clear All buttons that set CheckState directly
  • Copilot challenge: Ask Copilot to "add a 'Invert Selection' button that toggles every child CheckBox with Not chk.Checked"

Exercise 21.3 — Settings Persistence

  • Create a settings form with 3 groups of checkboxes: Display, Sound, Privacy
  • Load state from My.Settings on Form_Load
  • Use parent checkboxes to enable/disable sub-options in each group
  • Save to My.Settings on OK; revert to saved values on Cancel
  • Copilot challenge: Ask Copilot to "serialize all CheckBox states to a Dictionary(Of String, Boolean) keyed by .Name, then save as JSON to a user config file"

Next: Lesson 22 — RadioButton Control

Learn RadioButtons for mutually exclusive choices — Checked, CheckedChanged, grouping with GroupBoxes and Panels, and combining RadioButtons with CheckBoxes in real forms.

Continue »

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

CheckBox, RadioButton, and all WinForms controls covered with complete working programs.

View on Amazon →
VB Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

Real-world order forms and settings dialogs using CheckBox controls throughout.

View on Amazon →