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

时间:2014-11-11 14:06:31

标签: c# winforms checkbox datagridview

我找到了几篇相关文章并尝试过,但无法解决问题。我的winForm应用程序的datagridview中有一个复选框列。我想通过选中adjacant行的复选框来选择多行,并对选定的行执行一些操作。但我的行没有被选中。我的代码是:

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;
        }
    }

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

您需要处理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);
    }
}