Export (0) Print
Expand All

How to: Respond to Windows Forms CheckBox Clicks

Whenever a user clicks a Windows Forms CheckBox control, the Click event occurs. You can program your application to perform some action depending upon the state of the check box.

To respond to CheckBox clicks

  • In the Click event handler, use the Checked property to determine the control's state, and perform any necessary action.

    private void checkBox1_Click(object sender, System.EventArgs e)
    {
       // The CheckBox control's Text property is changed each time the 
       // control is clicked, indicating a checked or unchecked state.
       if (checkBox1.Checked)
       {
          checkBox1.Text = "Checked";
       }
       else
       {
          checkBox1.Text = "Unchecked";
       }
    }
    
    NoteNote

    If the user attempts to double-click the CheckBox control, each click will be processed separately; that is, the CheckBox control does not support the double-click event.

    NoteNote

    When the AutoCheck property is true (the default), the CheckBox is automatically selected or cleared when it is clicked. Otherwise, you must manually set the Checked property when the Click event occurs.

    You can also use the CheckBox control to determine a course of action.

To determine a course of action when a check box is clicked

  • Use a case statement to query the value of the CheckState property to determine a course of action. When the ThreeState property is set to true, the CheckState property may return three possible values, which represent the box being checked, the box being unchecked, or a third indeterminate state in which the box is displayed with a dimmed appearance to indicate the option is unavailable.

    private void checkBox1_Click(object sender, System.EventArgs e)
    {
       switch(checkBox1.CheckState)
       {
          case CheckState.Checked:
             // Code for checked state.
             break;
          case CheckState.Unchecked:
             // Code for unchecked state.
             break;
          case CheckState.Indeterminate:
             // Code for indeterminate state.
             break;
       }
    }
    
    NoteNote

    When the ThreeState property is set to true, the Checked property returns true for both Checked and Indeterminate.

Show:
© 2014 Microsoft