DataGridView:对所有选定的行应用编辑

Tar*_*aal 6 c# datagridview winforms

我有一个绑定到POCO对象列表的DataGridView.其中一个POCO属性是bool,由复选框表示.我想要的是能够选择多行,然后当我单击其中一个复选框时,所有突出显示的行都选中了它们的复选框.举例来说,如果你在VS 2010下使用TFS,我正试图在Pending Changes屏幕上复制行为.

我的问题是我找不到合适的事件来听.大多数DataGridView点击事件似乎都在列/行级别运行,我想要点击复选框时触发的内容.CellContentClick是最接近的,但是在取消选择行之后会触发,因此不会起作用.

有没有人有什么建议?

Mbt*_*925 12

当Checkbox值发生更改时,可以使用CurrentCellDirtyStateChanged.但是当这个事件触发时,选择的行将会消失.您应该做的就是在它之前保存选定的行.

一个简单的示例:您可以轻松完成它.

DataGridViewSelectedRowCollection selected;

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
    DataGridViewCell cell = dgv.CurrentCell;
    if (cell.RowIndex >= 0 && cell.ColumnIndex == 1) // My checkbox column
    {
        // If checkbox value changed, copy it's value to all selectedrows
        bool checkvalue = false;
        if (dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue != null && dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue.Equals(true))
            checkvalue = true;

        for (int i=0; i<selected.Count; i++)
            dgv.Rows[selected[i].Index].Cells[cell.ColumnIndex].Value = checkvalue;
    }

    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    selected = dataGridView1.SelectedRows;
}
Run Code Online (Sandbox Code Playgroud)