I want to use a CheckedListBox in an application where each item in the ListBox is the name of a folder on my hard drive and for the purpose of reading and writing text files to and from each of these folders I want to ensure that one and only one item (a folder) can be selected at any one time in the CheckedListBox
How can I achieve this via code in C#?
Thanks for reading 🙂
Edit \ Update – 22/10/2010
Thanks to all who took the time to reply – especially Adrift whose updated code as requested is working perfectly.
I do appreciate what some commentators said about my usage of a checkedlistbox in this manner, however I feel it suits my purposes perfectly in that I want there to be no doubt whatsoever as to where the text files will be read from and written to.
All the best.
I agree with the comments that radio buttons would be the usual UI element when only a single item is ‘checked’, but if you want to stick with a
CheckedListBoxfor your UI, you can try something like this:You also might want to set
CheckOnClicktotruefor theCheckedListBox.Edit
Updated the code per your comment to deselect an item if it is unchecked. The problem is that unchecking the previously checked item causes the event to fire again. I don’t know whether there is a standard way to handle this, but in the code below, I detach the handler before calling
SetItemCheck, then reattach the handler. It seems like a clean way to handle this, and it works. If I find that there is a recommended way to handle this, I will update my answer.HTH