Question

I have a simple IF statement in my code that i want to prompt the user if the item in index 2 of my checkedlistbox1 is selected.

It works when index 2 by itself is selected BUT does not work when other items including index 2 are checked in my checklist box. Below is what i have that works, now i just need it to work when 2 and others are selected.

if (checkedListBox1.SelectedIndex == 2)
{
   MessageBox.Show("Note to send email", "Note", MessageBoxButtons.OK);
}
Was it helpful?

Solution 2

You can use CheckedListBox.CheckedIndices instead.

Collection of checked indexes in this CheckedListBox.

foreach(int index in checkedListBox1.CheckedIndices)
{
  if(index == 2)
  {
     MessageBox.Show("Note to send email", "Note", MessageBoxButtons.OK);
  }
}

OTHER TIPS

Replace that code with

if (checkedListBox1.SelectedIndices.Contains(2))
{
   MessageBox.Show("Note to send email", "Note", MessageBoxButtons.OK);
}

That will check if 2 is among all selected items.

See more on SelectedIndices property on MSDN.

Use SelectedIndices instead of SelectedIndex, it returns a collection of the selected indices. Just make sure that 2 is in there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top