【问题标题】:How to check a CheckBox in DataGridview that whether it is checked or not如何检查DataGridview中的CheckBox是否被选中
【发布时间】:2014-04-20 16:39:19
【问题描述】:
我在 Windows 窗体的 DataGridView 中有 13 个 CheckBox,我想在选中第一个 CheckBox 时检查所有 CheckBox,并在未选中第一个 CheckBox 时取消选中所有 CheckBox,那么我该怎么做。我的代码适用于检查所有复选框,但在取消选中时失败。
我正在使用 CellContentClick 事件。
这是我的代码
if (e.ColumnIndex == 1)
{
for (int k = 2; k <= 13; k++)
{
DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[k];
DataGridViewCheckBoxCell checkCell = cell as DataGridViewCheckBoxCell;
checkCell.Value = true;
}
}
【问题讨论】:
标签:
c#
checkbox
datagridview
【解决方案1】:
试试这个:
if (e.ColumnIndex == 1)
{
DataGridViewCheckBoxCell firstCell =
dataGridView1.Rows[e.RowIndex].Cells[1] as DataGridViewCheckBoxCell;
if(firstCell == null)
{
return;
}
for (int k = 2; k <= 13; k++)
{
DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[k];
DataGridViewCheckBoxCell checkCell = cell as DataGridViewCheckBoxCell;
checkCell.Value = firstCell.Value;
}
}
【解决方案2】:
您使用 for 循环仅分配 true 值,您还需要将 false 值分配给复选框取消选中您的所有复选框..
if (e.ColumnIndex == 1)
{
for (int k = 2; k <= 13; k++)
{
DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[k];
DataGridViewCheckBoxCell checkCell = cell as DataGridViewCheckBoxCell;
checkCell.Value = dataGridView1.Rows[1].Cells[1].Value;
}
}