gomesh munda
gomesh munda

Reputation: 850

Index of items in a checkedlistbox using c# in winforms

I have 10 items in a checkedlist box. I believe that the index of the 1st element is 0, index of 2nd element is 1 and so on until index 9.My requirement is to find the true index of the elements as they occur in the list when i check them.Presently i'm using the following code but its not producing desired result. For example when i check the very 1st element no ,message is shown.When i check the 2nd element, the message says index 0 is checked.When i check the 10th element it says index 1 is checked....Whats wrong with my code?Please advice.

   private void clbAnnually_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        foreach (int indexChecked in clbAnnually.CheckedIndices)
        {
            MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked");

        }
    }

Upvotes: 2

Views: 105

Answers (1)

Ian
Ian

Reputation: 30813

The way to solve it is a bit tricky, this is because the Item will be checked after the ItemCheck event. Hence, you actually got to check if your current SelectedIndex during the ItemCheck event is not among the CheckedIndices to show that it currently is the one checked:

private void clbAnnually_ItemCheck(object sender, ItemCheckEventArgs e) {           
    if (!checkedListBox1.CheckedIndices.Contains(clbAnnually.SelectedIndex))
        MessageBox.Show("Index#: " + checkedListBox1.SelectedIndex.ToString() + ", is checked");
}

Upvotes: 2

Related Questions