For the original question the Solution 2 given by
SAKryukov is good.
For the requirement
use the option checkedListBox1.CheckedItems.Count and beyond a certain value of more items will not be selected.
stated by OP in the comment to Solution 2, one of the following Options can be used.
1. By deriving from the CheckedListBox
class
Subclass the
CheckedListBox
as
LimitedSelectCheckedListBox
. In the subclass add a Property
MaxSelectCount
to hold the maximum number of selections allowed.
In the constructor set the default value of this property. Say 1.
Override the
OnItemCheck
method and set the
NewValue
to
Unchecked
if the
CheckedItems.Count == MaxSelectCount.
Set the
MaxSelectCount
property of the
LimitedSelectCheckedListBox
either in the designer or in the Code.
public class LimitedSelectCheckedListBox : CheckedListBox{
public int MaxSelectCount { get; set; }
public LimitedSelectCheckedListBox() {
CheckOnClick = true;
MaxSelectCount = 1;
}
protected override void OnItemCheck(ItemCheckEventArgs ice) {
if (CheckedItems.Count == MaxSelectCount)
ice.NewValue = CheckState.Unchecked;
else
base.OnItemCheck(ice);
}
}
2. Subscribe to the CheckedListBox.ItemCheck
and disable selection
int maxSelectCount
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
maxSelectCount = 3;
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
if ((sender as CheckedListBox).CheckedItems.Count == maxSelectCount)
e.NewValue = CheckState.Unchecked;
}