2

我想遍历一个选中的列表框,看看返回了哪些值。没问题,我知道我可以做到:

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. Control c是否有另一种方法可以访问我选择的控件的该属性并且我看错了?先感谢您。

此致,

4

1 回答 1

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
      }
   }
于 2010-06-24T08:52:36.850 回答