Reputation: 67
I have a CheckedBoxList an I want to limit the selection (checked) that you can select, for exapmle only 2 of 10 items in the Box. There are not really 10, it could also be 13 etc.
I tried already with this code, but here I can select only one Item (I want select more than one Item but not all).
private void checkedListBox_ListOfCars_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
for (int ix = 0; ix < checkedListBox_ListOfCars.Items.Count; ++ix)
{
if (e.Index != ix) checkedListBox_ListOfCars.SetItemChecked(ix, false);
}
}
}
Upvotes: 0
Views: 261
Reputation: 868
You can do this by adding a variable for the form like
int checkedItemsLimit = 2; // As you wrote in your question. This number is just an example.
Every time when something is checked at the ItemCheck event you can check if the numbers of checked items in the checkListBox_ListOfCars
is equal to checkedItemsLimit
. If this is present then unchecked the last checked. The code will look like that:
private void checkedListBox_ListOfCars_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
if (checkedListBox_ListOfCars.CheckedItems.Count == checkedItemsLimit)
{
e.NewValue = CheckState.Unchecked;
}
}
}
Upvotes: 2