c#通过复选框在datagridview中选择多行

本文关键字:选择 datagridview 复选框 | 更新日期: 2023-09-27 18:29:58

我找到了几篇相关的文章并尝试了它们,但都无法解决问题。我在winForm应用程序的数据网格视图中有一个复选框列。我想通过选中相邻行的复选框来选择多行,并对所选行执行一些操作。但是我的行没有被选中。我的代码是:

this.dgvLoadTable.CellClick += new DataGridViewCellEventHandler(dgvLoadTable_CellClick);
private void dgvLoadTable_CellClick(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dgvLoadTable.Rows)
        {
            //If checked then highlight row
            if (Convert.ToBoolean(row.Cells["Select"].Value))// Select is the name 
                                                             //of chkbox column
            {
                row.Selected = true;
                row.DefaultCellStyle.SelectionBackColor = Color.LightSlateGray;
            }
            else
                row.Selected = false;
        }
    }

我在这里做错了什么?

c#通过复选框在datagridview中选择多行

您需要处理CellValueChanged事件而不是CellClick事件:

private void dgvLoadTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    foreach (DataGridViewRow row in dgvLoadTable.Rows)
    {
        if (row.Cells[3].Value != null && row.Cells[3].Value.Equals(true)) //3 is the column number of checkbox
        {
            row.Selected = true;
            row.DefaultCellStyle.SelectionBackColor = Color.LightSlateGray;
        }
        else
            row.Selected = false;
    }
}

并添加CurrentCellDirtyStateChanged事件:

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