Winforms 如何计数WindowsForms应用程序中DataGridView中的复选框计数
我有一个DataGridView。在该复选框列中有。如果我想选中DataGrid视图中的复选框,一个按钮是可见的,如果没有选中复选框,按钮将被启用,如果我选中超过5个复选框,一个警告将出现,我尝试这样做Winforms 如何计数WindowsForms应用程序中DataGridView中的复选框计数,winforms,datagridview,Winforms,Datagridview,我有一个DataGridView。在该复选框列中有。如果我想选中DataGrid视图中的复选框,一个按钮是可见的,如果没有选中复选框,按钮将被启用,如果我选中超过5个复选框,一个警告将出现,我尝试这样做 private void GridView1_CellClick(object sender, DataGridViewCellEventArgs e) { DataGridViewCheckBoxCell ch1 = new DataGridVi
private void GridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)GridView1.Rows[GridView1.CurrentRow.Index].Cells[0];
if (ch1.Value == null)
{
btnShow.Visible = false;
}
else
btnShow.Visible = true;
}
在这里我没有得到确切的输出。我如何才能解决这个问题请帮助
CellContentClick
而不是CellClick
。复选框
值仅在前者中更改时触发CurrentCell
而不是当前行Cells[0]
,否则,即使在同一行中单击了与CheckBoxCell
不同的单元格,也会不必要地触发此代码CheckBoxCell
(选中/未选中),则遍历行以计算正确列中选中的单元格数。单元格.Value
可以是null
、true
或false
,当前单击的单元格将不会反映新值。因此,请改用Cell.EditedFormattedValue
,它将具有更新的值,并且始终为true
或false
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if ((dataGridView1.CurrentCell as DataGridViewCheckBoxCell) != null)
{
int count = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
bool isChecked = (bool)row.Cells[0].EditedFormattedValue;
if (isChecked)
{
count++;
}
}
btnShow.Visible = count > 0; // Whatever your condition may be.
if (count > 5)
{
// Your caution here. For example:
MessageBox.Show(this, "Danger, Will Robinson!", "Caution");
}
}
}
尝试查看选中并取消选中该复选框时得到的值。我不确定,但我认为关于
null
。你们真的得到空值了吗?复选框被取消选中了吗?若ch1.value=true
@nelek:若我选中第一次按钮将不会出现。经过多次尝试后,若复选框被取消选中,按钮是否会被选中Displayed@Fabio:如果use ch1.Value=true,则显示like无法将类型对象隐式转换为Bool。请检查此项: