Allow the user to select a limited number of CheckBoxes in C#

This example lets the user select up to 2 of the CheckBoxes. 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, the program unchecks the CheckBox that has been in the list the longest. (That triggers that control's CheckedChanged event handler which removes it from the list.)

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

   

 

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.