我找到了几篇相关文章并尝试过,但无法解决问题。我的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;
}
}
我在这里做错了什么?
答案 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);
}
}