首页 > 解决方案 > CheckListBox SelectedItems.Count 并不总是有效

问题描述

我有一个包含三个 CheckedListBoxes 的对话框。

为了让最终用户更容易,我有一个“全部”复选框,它将选择“它”对应的列表框中的所有项目。

在此处输入图像描述

该功能工作得很好。

在将控制权返回给调用表单之前,我想确保用户在前两个列表复选框中至少选择了一项。

我遇到的问题是用户单击“确定”按钮时的验证代码。

如果用户单击其中一个 listcheckboxes 中的单个行,则该 listcheckbox selecteditem.count方法的返回值不为零,但是当我使用 listcheckbox SetItemChecked方法设置所有行时,它为零。

这是我编写的代码,用于在选中“全部”复选框时选择所有行。

  // set all the items to be selected.
    private void chkAllFields_CheckedChanged(object sender, EventArgs e)
    {
        bool CheckState = chkAllFields.Checked;

        for (int i = 0; i < checkedListFields.Items.Count; i++)
            checkedListFields.SetItemChecked(i, CheckState);


    }

这是我检查是否至少选择了一行的代码。

// see if any fields have been selected.
        if (checkedListFields.SelectedItems.Count == 0)
        {
            MessageBox.Show("Please select at least one field to include", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            this.DialogResult = DialogResult.None;  // don't allow this form to close
        }
        else

以前有没有人经历过这种情况,如果有,有没有办法解决这个问题?

我添加了使用 CheckListBox GetItemChecked 方法来查看是否选择了任何行的逻辑。虽然如果我手动选择一行,则此逻辑有效,但当我尝试使用 SetItemChecked 方法以编程方式选择 CheckListBox 中的所有行时,问题仍然存在。

   // see if any of the rows in the passed items is checked
    private bool AtLeastOneItemsChecked(CheckedListBox ListBox)
    {
        try
        {
            for (int i = 0; i < ListBox.Items.Count; i++)
            {
                if (ListBox.GetItemChecked(i) == true)
                    return true;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        return false;
    }

标签: c#

解决方案


您可能会混淆selectedchecked

与您的预期相反,SelectedItems 和 SelectedIndices 属性并不能确定检查哪些项目;他们确定突出显示哪些项目。

文档显示了如何检查检查了多少条目的示例:

// Determine if there are any items checked.  
if(checkedListBox1.CheckedItems.Count != 0)  
{  
   // If so, loop through all checked items and print results.  
   string s = "";  
   for(int x = 0; x <= checkedListBox1.CheckedItems.Count - 1 ; x++)  
   {  
      s = s + "Checked Item " + (x+1).ToString() + " = " + checkedListBox1.CheckedItems[x].ToString() + "\n";  
   }  
   MessageBox.Show (s);  
}

推荐阅读