Reputation: 297
namespace explorer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DirectoryInfo di = new DirectoryInfo("c:\\test");
FileSystemInfo[] files = di.GetFileSystemInfos();
checkedListBox1.Items.AddRange(files);
}
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);
}
//removed irrelevant parts of the code
}
}
I forgot how to build an event handler for the checkedlistbox. I need one selected. I have multiple files but I need just one selected by a check box.
Upvotes: 0
Views: 167
Reputation: 81675
You need to turn off the event handler or use a variable as a flag to avoid a stack overflow since you are unchecking items in an ItemCheck event:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
if (ix != e.Index) {
checkedListBox1.SetItemChecked(ix, false);
}
}
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
An example using a variable:
bool checkFlag = false;
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
if (!checkFlag) {
checkFlag = true;
for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix) {
if (ix != e.Index) {
checkedListBox1.SetItemChecked(ix, false);
}
}
checkFlag = false;
}
}
Upvotes: 2
Reputation: 8704
You can create List<FileSystemInfo>
collection and add every checked file to it on check and remove on uncheck. The handler itself is already created as i see(checkedListBox1_ItemCheck
). May be you should consider to write the question more clearly, because may be i understood you not exactly right?
Upvotes: 1