如何遍历通过Windows控件访问的选中列表框?

时间:2010-06-24 08:49:21

标签: c# forms loops checkedlistbox

我想循环检查列表框并查看返回的值。这没问题,我知道我可以用:

if(myCheckedListBox.CheckedItems.Count != 0)
{
   string s = "";
   for(int i = 0; i <= myCheckedListBox.CheckedItems.Count - 1 ; i++)
   {
      s = s + "Checked Item " + (i+1).ToString() + " = " + myCheckedListBox.CheckedItems[i].ToString() + "\n";
   }
   MessageBox.Show(s);
}

问题是我在使用代码生成后检查列表框。我循环遍历表格中的每个控件(在表单上),当控件是一个选中的列表框时,我需要它来使用我上面编写的代码(或类似代码)。这就是我循环控制的方式:

   foreach (Control c in table.Controls)
    {
        if (c is TextBox)
        {
            // Do things, that works
        }
        else if (c is CheckedListBox)
        {
            // Run the code I've written above
        }

问题是,当我尝试访问这样的控件时:if (c.CheckedItems.Count != 0),它甚至找不到CheckedItems的{​​{1}}属性。有没有其他方法可以访问我选择的控件的属性,我是否错误地看着它?提前谢谢。

您诚挚的,

1 个答案:

答案 0 :(得分:3)

您需要将c转换为CheckedListBox:

((CheckedListBox)c).CheckedItems;

或者,如果要保留对正确类型的引用,则可以执行以下操作:

CheckedListBox box = c as CheckedListBox;
int count = box.CheckItems.Count;
box.ClearSelected();

如果你使用了第一个例子,它将是这样的:

int count = ((CheckedListBox)c).Count;
((CheckedListBox)c).ClearSelected();

显然,当你需要对强制转换控件进行多次操作时,第二个例子会更好。

<强>更新

   foreach (Control c in table.Controls)
   {
      if (c is TextBox)
      {
         // Do things, that works
      }
      else if (c is CheckedListBox)
      { 
         CheckedListBox box = (CheckedListBox)c;
         // Do something with box
      }
   }
相关问题