繁体   English   中英

CheckListBox SelectedItems.Count并不总是有效

[英]CheckListBox SelectedItems.Count doesn't always work

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

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

在此处输入图片说明

该功能工作正常。

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

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

如果用户单击listcheckbox之一中的单个行,则该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;
    }

您可能会混淆所选与已检查

与您可能期望的相反,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);  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM