[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use a tristate CheckBox in C#

[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 control'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 control'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 in the program's ListBox when the states change. The program uses the same event handler for all three CheckBox controls.

// 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); }

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.