Winforms 如何计数WindowsForms应用程序中DataGridView中的复选框计数

Winforms 如何计数WindowsForms应用程序中DataGridView中的复选框计数,winforms,datagridview,Winforms,Datagridview,我有一个DataGridView。在该复选框列中有。如果我想选中DataGrid视图中的复选框,一个按钮是可见的,如果没有选中复选框,按钮将被启用,如果我选中超过5个复选框,一个警告将出现,我尝试这样做 private void GridView1_CellClick(object sender, DataGridViewCellEventArgs e) { DataGridViewCheckBoxCell ch1 = new DataGridVi

我有一个DataGridView。在该复选框列中有。如果我想选中DataGrid视图中的复选框,一个按钮是可见的,如果没有选中复选框,按钮将被启用,如果我选中超过5个复选框,一个警告将出现,我尝试这样做

 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。请检查此项: