如何在 C# 中更改复选框值时计算 DataGridView 中选中的复选框?

How to count checked checkboxes in DataGridView when Checkbox value is changed in c#?

我无法计算 DataGridView 中选中的复选框。我想在选中复选框期间计算选中的复选框并将选中的项目数存储在标签中。我尝试了以下代码,但没有给出正确的计数:

    int num = 0;
    private void dgvLoadData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        bool isChecked = Convert.ToBoolean(dgvLoadData.Rows[dgvLoadData.CurrentCell.RowIndex].Cells[0].Value.ToString());

        if (isChecked)
        {
            num+=1;
        }
        else
        {
            num-=1;
        }

        labelSelectedSum.Text = "Selected Items: " + num;
    }

在 table 上应用 CurrentCellDirtyStateChanged 事件。调用 gridview.CommitEdit 更新复选框列的值。执行以下操作:

private void dgvLoadData_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvLoadData.IsCurrentCellDirty)
    {
        dgvLoadData.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

这将调用 _CellValueChanged 事件。不会对 CellValueChanged 事件中的代码进行任何更改:

int num = 0;
private void dgvLoadData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0)
            return;
    bool isChecked = (bool)dgvItemsToShip.Rows[e.RowIndex].Cells[0].Value;

    if (isChecked)
    {
        num+=1;
    }
    else
    {
        num-=1;
    }

    labelSelectedSum.Text = "Selected Items: " + num;
}

您可以使用事件:CellContentClick 和 CellContentDoubleClick:

祝你好运!

int num = 0;
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        bool isChecked = (bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;
        CheckCount(isChecked);
    }
    private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        bool isChecked = (bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;
        CheckCount(isChecked);
    }
    private void CheckCount(bool isChecked)
    {
        if (isChecked)
        {
            num++;
        }
        else
        {
            num--;
        }
        labelSelectedSum.Text = "Selected Items: " + num;
    }

我有一个 DataTable 绑定到我的 DataGridView,我检查第一列是否选中了任何复选框 这是我的例子:

private void dataGridViewMain_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
  if (e.ColumnIndex == 0)
  {
    int numberOfRow = dataTableCsvFile.AsEnumerable().Count(r => r[0].ToString() == true.ToString());
    buttonDataGridviewVerify.Enabled = numberOfRow > 0;
  }
}