繁体   English   中英

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

[英]c# selecting multiple rows in datagridview by checkbox

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

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

我在这里做错了什么?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM