[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[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]

[C# 5.0 Programmer's Reference]

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

Title: Allow limited CheckBox selection in C#

[Allow limited CheckBox selection in C#]

Normally the user can check or uncheck any CheckBox independently of any other selections. This post shows how you can allow limited CheckBox selection. In this example the user can select up to 2 of the CheckBoxes.

Whenever the user clicks a CheckBox, you could look through the CheckBoxes and make sure that only two were selected. Unfortunately that would require the user to select options in a particular order. For example, if you simply looped through the CheckBoxes in order and kept the first two choices, then it would be hard for the user to make choices later in the list.

This example uses a different approach to allow limited CheckBox selection. It keeps a list of the CheckBoxes selected. When you make a new selection, the program loops through the list and unchecks the oldest selection. That way the user can make selections in any order and the latest selections are preserved.

All of the CheckBoxes use the following event handler to manage the selections.

// The selected CheckBoxes. private int NumAllowedOptions = 2; private List Selections = new List(); // Make sure we don't have too many options selected. private void chkOption_CheckedChanged(object sender, EventArgs e) { CheckBox chk = sender as CheckBox; if (chk.Checked) { // Add this selection. Selections.Add(chk); // Make sure we don't have too many. if (Selections.Count > NumAllowedOptions) { // Remove the oldest selection. Selections[0].Checked = false; } } else { // Remove this selection. Selections.Remove(chk); } }

The Selections list holds the currently checked CheckBoxes.

When the user checks or unchecks a box, the event handler updates the list. If the CheckBox is checked, the code adds it to the list. If the number of CheckBoxes in the list greater than the allowed number (2 in this example), the program unchecks the CheckBox that has been in the list the longest. (That triggers that control's CheckedChanged event handler which makes the following code remove it from the list.)

If the newly toggled CheckBox is unchecked, the event handler removes it from the list.

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

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