Use a tristate CheckBox in C#

Normally a CheckBox is either checked or unchecked. You can catch the CheckedChanged event handler to learn when the control's value has changed and you can use its Checked property to get its current value.

A CheckBox can also display a third indeterminate state. For example, a program might use the three states to indicate that a group of options is selected (checked), not selected (unchecked), or some options are selected (indeterminate).

To do this, first set the ComboBox's ThreeState property to True. Next catch the control's CheckStateChanged event instead of CheckedChanged. In the event, use the control's CheckState property to see whether it is checked, unchecked, or indeterminate.

The following code shows how this example sets the lunch ComboBox's state to indeterminate when the program starts.

// Make lunch indeterminate.
private void Form1_Load(object sender, EventArgs e)
{
chkLunch.CheckState = CheckState.Indeterminate;
}

The following code shows how the program displays CheckBox states when they change. The program uses the same event handler for all three CheckBoxes.

// Display the CheckBox's current state.
private void chkMeal_CheckStateChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox;
lstState.Items.Add(chk.Text + ": " + chk.CheckState);
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.