【问题标题】:iterate through checkedListBox testing for checked - cast error遍历checkedListBox测试检查 - 强制错误
【发布时间】:2013-01-30 02:55:51
【问题描述】:

我正在尝试检查checkedlistbox 中的每个项目,并根据它是否被选中来处理该项目。我已经能够使用 indexCollection 获取已检查的项目,但我无法获取所有项目,我收到此错误“无法将“System.String”类型的对象转换为“System.String”类型。 Windows.Forms.ListViewItem'

        foreach (ListViewItem item in checkedListBox2.Items)
        {
            if (item.Checked == true)
                //do something with item.name

            else
                //do something else with item.name
        }

我不确定为什么它在 foreach 行中给我字符串转换错误。我怎样才能做到这一点?谢谢。

【问题讨论】:

    标签: winforms foreach checkedlistbox


    【解决方案1】:

    如果您允许复选框具有 Indeterminate 状态,那么您应该使用GetItemCheckState 方法来检索复选框的状态

    for (int i = 0; i < checkedListBox2.Items.Count; i++) 
    {
         CheckState st = checkedListBox2.GetItemCheckState(checkedListBox2.Items.IndexOf(i));
         if(st == CheckState.Checked)
            ....
         else if(st == CheckState.Unchecked)
            ....
         else
            ... // inderminate
    }        
    

    否则就足以调用 GetItemChecked 返回真/假值(对于不确定状态也为真)

    【讨论】:

      【解决方案2】:

      CheckedListBox.Items 包含objects 的集合,而不是ListViewItem 的集合

      你可以这样检查

              for (int i = 0; i < checkedListBox2.Items.Count; i++)
              {
                  if (checkedListBox2.GetItemChecked(i))
                  {
                      //do something with checkedListBox2.Items[i]
                  }
                  else
                  {
                      //do something else with checkedListBox2.Items[i]
                  }
              }
      

      【讨论】:

        【解决方案3】:

        如果您允许复选框具有 Indeterminate 状态,那么您应该使用GetItemCheckState 方法来检索复选框的状态

        for (int i = 0; i < checkedListBox2.Items.Count; i++) 
        {
             CheckState st = checkedListBox2.GetItemCheckState(i);
             if(st == CheckState.Checked)
                ....
             else if(st == CheckState.Unchecked)
                ....
             else
                ... // inderminate
        }        
        

        否则就足以调用 GetItemChecked 返回真/假值(对于不确定状态也为真)

        【讨论】:

        • 谢谢,非常有用的代码
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-09
        • 2023-03-07
        • 2020-11-25
        • 2013-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多