CheckedListBox - How to programmatically ensure that one and only one item can be checked at any given time?

I want to use CheckedListBox in an application where each item in the ListBox is the name of a folder on my hard drive and for reading and writing text files to and from each of these folders I want one and only one item (folder) to be selected in any moment in CheckedListBox

How can I achieve this with C # code?

Thanks for reading: -)

Edit \ Update - 10/22/2010 Thanks to everyone who took the time to respond - especially Adrift, whose updated code on request works fine.

I understand that some commentators have talked about my use of checklistbox in this way, however I feel that it is ideal for my purposes as I want there to be no doubt about where the text files will be read and written to.

All the best.

+3
source share
1 answer

I agree with the comments that the switches will be a normal user interface element when only one element is β€œchecked”, but if you want to stick CheckedListBoxwith your user interface, you can try something like this:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;

    if (checkedIndices.Count > 0 && checkedIndices[0] != e.Index)
    {
        checkedListBox1.SetItemChecked(checkedIndices[0], false);
    }
}

You can also install CheckOnClickin truefor CheckedListBox.

Edit

, , . , . , , SetItemCheck, . , . , , .

HTH

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;

    if (checkedIndices.Count > 0)
    {
        if (checkedIndices[0] != e.Index)
        {
            // the checked item is not the one being clicked, so we need to uncheck it.  
            // this will cause the ItemCheck event to fire again, so we detach the handler, 
            // uncheck it, and reattach the handler
            checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
            checkedListBox1.SetItemChecked(checkedIndices[0], false);
            checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
        }
        else
        {
            // the user is unchecking the currently checked item, so deselect it
            checkedListBox1.SetSelected(e.Index, false);
        }
    }
}
+6

Source: https://habr.com/ru/post/1770619/


All Articles