用于检查更改的 DataGridView 事件

Mah*_*ari 2 c# events datagridview winforms

我有一个DataGridView包含一堆列和一个名为IsChecked的 checkBoxColumn 。

我想每当行的检查状态发生变化时引发一个事件。当用户单击复选框或在一行上按空格键时,可以选中或取消选中一行。

这就是我将 checkBoxColumn 添加到网格中的方法:

dgvMain.Columns.Add(new DataGridViewCheckBoxColumn { 
            Name = "IsChecked" , 
            Width = 20, 
            Visible = false,
            HeaderText = "",
            SortMode = DataGridViewColumnSortMode.NotSortable,
            DisplayIndex = Columns.Count, //to be displayed as last column
            ValueType = typeof(bool),
            FalseValue = false,
            TrueValue = true
        });
Run Code Online (Sandbox Code Playgroud)

这就是我在按下空格键时检查单元格的方法:

private void dgvMain_KeyDown(object sender, KeyEventArgs e)
{
     foreach (DataGridViewRow row in dgvMain.SelectedRows)
     {
         bool? checkState = (bool?)row.Cells["IsChecked"].Value;
         if (checkState == null || checkState == false)
             checkState = true;
         else
             checkState = false;
         row.Cells["IsChecked"].Value = checkState;
     }

}
Run Code Online (Sandbox Code Playgroud)

尝试#1:
我尝试使用CellEndEdit事件,该事件仅在您使用鼠标检查单元格时有帮助,但是当我按空格并且单元格检查/取消选中时CellEndEdit不会触发。

尝试#2:
我尝试使用CellValueChanged事件,当我按空格时,以及当我使用鼠标选中该框并离开该行时,该事件工作正常,但当我多次选中并取消选中该框时,没有任何反应。CellValueChanged当单元格完成鼠标编辑时,它似乎会引发。

尝试#3:
我还尝试使用CurrentCellDirtyStateChanged它响应由鼠标引起的第一个检查的更改,但不响应鼠标的快速检查的更改,仅响应第一个以及当您离开该行时。我想捕获所有选中的更改,即使用户通过单击复选框快速更改选中状态,这也很重要。

我不确定是否已经为此目的举办过任何活动。如果没有,如何以编程方式为此列添加事件处理程序?

Jun*_*ith 6

CurrentCellDirtyStateChanged事件处理程序中,触发,EndEdit以便触发值更改事件。

void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dataGridView1.IsCurrentCellDirty && dataGridView1.CurrentCell.ColumnIndex == CheckColumnIndex)
    {
        dataGridView1.EndEdit();
    }
}
Run Code Online (Sandbox Code Playgroud)

CellValueChanged事件处理程序中从 CheckBoxColumn 获取值。

void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == CheckColumnIndex)
    {
        DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
        bool achecked = Convert.ToBoolean(checkCell.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)