c# - 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;
}
解决方案
与您的预期相反,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);
}
推荐阅读
- php - How to convert two single dimensional arrays into one multi-dimensional array - PHP
- python - 使用自定义估计器绘制验证和训练准确性
- apache-spark - Spark 性能从 Dataframe 保存到 hdfs 或 hive 的大型数据集
- sql-server - 我们可以使用 Execute Sql 任务截断 Excel 工作表中的数据吗?
- java - 从 Spring Boot 为 Angular 应用程序生成 jwt 令牌
- php - 如何覆盖默认 Psr\LogLoggerInterface 别名
- php - 如何根据用户是否登录显示或隐藏信息
- android - 如何在地图上的标记片段中设置图像
- ruby-on-rails - 单击编辑按钮后,之前上传的文件未显示在 Rails 表单上
- continuous-integration - travis: sh: 0: 无法打开 /etc/init.d/xvfb