【问题标题】:DataGridView: Apply an edit to all selected rowsDataGridView:将编辑应用于所有选定的行
【发布时间】:2012-03-14 13:32:28
【问题描述】:

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

我的问题是我找不到合适的活动来收听。大多数 DataGridView 单击事件似乎都在列/行级别运行,我想要在您单击复选框时触发的东西。 CellContentClick 是最接近的,但它会在 行被取消选择之后触发,所以这不起作用。

有人有什么建议吗?

【问题讨论】:

  • 你的意思是有一个全选复选框吗?
  • 不完全。假设您有六行,并且突出显示/选择了 4 行。然后单击其中一个突出显示的行中的复选框,将其状态更改为 Checked。现在应该检查所有四个选定的行,无论它们以前的状态如何。
  • 保持简单是我们的政策。当用户在网格中选择行时,为什么不将行数据项的属性值更改为 true。这会将 GUI 更新为绑定控件。

标签: c# winforms datagridview


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    这不是一个好的设计,但你可以尝试使用 MouseDown 事件(它将在网格更改选择之前触发)和 HitTest(知道用户点击的位置):

    private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {
        var hitTest = this.dataGridView1.HitTest(e.X, e.Y);
        if (hitTest.Type == DataGridViewHitTestType.Cell && hitTest.ColumnIndex == 0 /* set correct column index */)
        {
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            { 
                // Toggle
                row.Cells[0].Value = !((bool)row.Cells[0].Value);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-25
      • 2023-03-26
      • 2013-04-27
      • 1970-01-01
      • 2012-07-09
      • 2018-08-08
      • 2010-10-22
      • 2010-11-12
      相关资源
      最近更新 更多