【发布时间】:2019-01-31 15:47:48
【问题描述】:
我有一个 WinForm 应用程序,它具有 DataGridView,其中一列带有 CheckBox。 用复选框选择几行后,我需要迭代行并检查 CheckBox 是否被勾选。
我已经尝试过 for 和 foreach 循环,但每次 bx 的值都是真的! 有趣的是,我有一个选择全部的按钮和一个使用代码清除所有的按钮,而且它有效!
我创建 DataGridView 的代码:
ComputerSelection computerSelection = new ComputerSelection();
DataGridViewCheckBoxColumn checkBox = new DataGridViewCheckBoxColumn();
checkBox.ValueType = typeof(bool);
checkBox.Name = "CheckBox";
checkBox.HeaderText = "Select";
computerSelection.compGridView.Columns.Add(checkBox);
computerSelection.compGridView.Columns.Add("Name", "Name");
computerSelection.compGridView.Columns.Add("AgentVersion", "Agent Version");
computerSelection.compGridView.Columns.Add("Status", "Status");
computerSelection.compGridView.Columns.Add("Domain", "Domain");
迭代代码(我搜索的大多数帖子都共享该解决方案作为正确的解决方案):
foreach (DataGridViewRow row in computerSelection.compGridView.Rows)
{
if ((bool)row.Cells["CheckBox"].Value)
{
computerSelection.ComputersList.Add(row.Cells[1].Value.ToString());
}
}
即使在未选中的复选框上,此代码也始终返回 TRUE。我在 StackOverFlow 上搜索了很多帖子,甚至尝试使用 as DataGridViewCheckBoxCell 但没有成功。
选择所有按钮代码(使用相同的机制:():
private void SelectAllButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < compGridView.Rows.Count; i++)
{
compGridView.Rows[i].Cells[0].Value = true;
}
}
我需要在每次迭代后“row.Cells[1].Value.ToString()”代码将返回 false 或 true,而不总是 true。
【问题讨论】:
-
尝试通过索引 0 访问它,就像您在 SelectAll 函数中所做的那样,看看您是否得到不同的行为。设置断点以在强制转换之前查看值是什么。
-
@user7733611 已经尝试使用索引 0,但没有成功。还检查了您关于在转换之前检查值的建议,它仍然与转换后的值相同:(
标签: c#