【问题标题】:How to loop through checked list box you accessed through the windows controls?如何遍历通过 Windows 控件访问的选中列表框?
【发布时间】:2010-06-24 08:49:21
【问题描述】:

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

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),它甚至找不到Control cCheckedItems 属性。是否有另一种方法可以访问我选择的控件的该属性并且我看错了?提前谢谢你。

此致,

【问题讨论】:

    标签: c# forms loops checkedlistbox


    【解决方案1】:

    您需要将 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
          }
       }
    

    【讨论】:

    • 感谢您的回复,但我应该把它放在哪里?
    • 第二个确实有效,但我不确定如何或在哪里使用第一个。尽管如此,它仍然有效。谢谢!
    • @Kevin - 你是什么意思?看,如果您有一个 CheckedListBox 控件,您只需将其转换为 CheckedListBox 即可访问 CheckedListBox 属性?
    • 我试过了:if ((CheckedListBox)c.CheckedItems.Count != 0),但我遇到了和以前一样的问题。投射它不会让我访问该属性。但是,c as CheckedListBox(您的 box 示例)工作正常。我在这里做错了吗?
    • 是的,你做错了。应该是:if (((CheckedListBox)c).CheckedItems.Count != 0).
    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2012-12-03
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多