在winforms中使用c#在checkedlistbox中索引项目

问题描述:

我在一个检查列表框中有 10 个项目.我相信第一个元素的索引是 0,第二个元素的索引是 1,依此类推,直到索引 9.我的要求是找到元素的真实索引,当我检查它们时,它们出现在列表中.现在我'm 使用以下代码,但没有产生预期的结果.例如,当我检查第一个元素时,没有显示消息.当我检查第二个元素时,消息说索引 0 被检查.当我检查第 10 个元素时,它说索引 1 被检查......我的有什么问题代码?请指教.

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");

        }
    }

解决的方法有点棘手,这是因为Item会在之后被检查ItemCheck 事件.因此,您实际上必须在 ItemCheck 事件期间检查您当前的 SelectedIndex 是否notCheckedIndices 中以显示它当前是被检查的:

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");
}