CheckBox Control
The CheckBox control allows users to select or deselect an option. It's perfect for Yes/No, True/False, or On/Off choices.
What is a CheckBox?
A CheckBox is a control that displays a check mark when selected. Users can click it to toggle between checked and unchecked states. Unlike RadioButtons, CheckBoxes are independent - checking one doesn't uncheck others.
Common uses: "I agree to terms", "Remember me", "Enable notifications", "Show password", and other Yes/No options.
How to Use
- Drag and drop a CheckBox from the Toolbox onto your form.
- Rename it (e.g.,
chkAgree,chkRemember). - Set the Text property to what users will see.
- Set the Checked property to
trueif you want it checked by default. - Double-click to create a CheckedChanged event handler.
Code Example
// 1. Drag a CheckBox onto the form
// 2. Set properties in the designer:
// - Name: chkAgree
// - Text: I agree to the terms
// - Checked: false
// 3. Double-click to create CheckedChanged event
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
// Enable or disable a button based on the checkbox
btnSubmit.Enabled = chkAgree.Checked;
}
// 4. Check the state in code
if (chkAgree.Checked)
{
MessageBox.Show("User agreed to terms");
}
else
{
MessageBox.Show("User did not agree");
}
Important Properties
| Property | Description | Example |
|---|---|---|
Text |
The text displayed next to the checkbox | chkAgree.Text = "I agree"; |
Checked |
Whether the checkbox is checked | chkAgree.Checked = true; |
CheckState |
Can be Checked, Unchecked, or Indeterminate | chkAgree.CheckState = CheckState.Indeterminate; |
ThreeState |
Allows three states (checked, unchecked, indeterminate) | chkAgree.ThreeState = true; |
AutoCheck |
Whether the checkbox toggles automatically on click | chkAgree.AutoCheck = false; |
Appearance |
Normal or Button appearance | chkAgree.Appearance = Appearance.Button; |
Exercise
Task: Create a pizza order form with checkboxes for toppings.
- Create a new Windows Forms project.
- Add a Label: "Select your pizza toppings".
-
Add CheckBox controls for:
- Pepperoni
- Mushrooms
- Onions
- Extra Cheese
- Olives
- Add a Button: "Order Pizza".
- When clicked, show a message with all selected toppings.
- Add a "Select All" checkbox that checks/unchecks all toppings.
Key Takeaway
CheckBoxes are perfect for independent Yes/No choices. Use the Checked property
to read the state and the CheckedChanged event to respond to changes.