In my CheckedListBox
app I want to allow only a single item to be checked.
I have these properties already set
checkOnClick = true;
SelectionMode = One;
Any advise will be appreciated
In my CheckedListBox
app I want to allow only a single item to be checked.
I have these properties already set
checkOnClick = true;
SelectionMode = One;
Any advise will be appreciated
uncheck all other items in ItemCheck event as below :
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix)
if (ix != e.Index) checkedListBox1.SetItemChecked(ix, false);
}
the best way to do this is like this:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked && checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0], false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
}
no looping is always better.
We can also do this by checkedListBox1_SelectedIndexChanged Event.
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int idx = checkedListBox1.SelectedIndex;
for(int i=0;i<checkedListBox1.Items.Count;i++)
{
if(i != idx)
{
checkedListBox1.SetItemChecked(i, false);
}
}
}
Updated to Visual 2019
protected void chb_list_SelectedIndexChanged(object sender, EventArgs e)
{
int idx = chb_list.SelectedIndex;
for (int i = 0; i < chb_list.Items.Count; i++)
{
if (i != idx)
{
chb_list.Items[i].Selected = false;
}
}
}
© 2022 - 2024 — McMap. All rights reserved.