C# 如何在选中单元格后停止DataGridView编辑?
我使用C# 如何在选中单元格后停止DataGridView编辑?,c#,checkbox,datagridview,contextmenustrip,C#,Checkbox,Datagridview,Contextmenustrip,我使用DataGridView上的ContexMenuStrip删除了一些行,但它不能正常工作 每次如果我选中3行,在选择ContexMenuStrip后,它只删除2行。当我在不使用正常工作的ContexMenuStrip(通过按钮)的情况下执行此代码时 当我看到该行为时,我理解当前行正在编辑,但尚未完成。双击当前行停止编辑myContexMenuStrip后,该功能正常工作 如何在选中复选框后停止编辑?选择并编辑单元格后,DataGridView属性IsCurrentCellDirty设置为
DataGridView
上的ContexMenuStrip
删除了一些行,但它不能正常工作
每次如果我选中3行,在选择ContexMenuStrip
后,它只删除2行。当我在不使用正常工作的ContexMenuStrip
(通过按钮
)的情况下执行此代码时
当我看到该行为时,我理解当前行正在编辑,但尚未完成。双击当前行停止编辑myContexMenuStrip
后,该功能正常工作
如何在选中
复选框后停止编辑?选择并编辑单元格后,DataGridView
属性IsCurrentCellDirty
设置为True
。如果在DataGridViewCheckBoxCell
上发生此状态更改时捕获事件处理程序,则可以调用以立即完成这些更改
this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;
private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.dataGridView1.IsCurrentCellDirty && this.dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
{
this.dataGridView1.EndEdit();
}
}
进一步解释:
无论何时编辑当前单元格,都会在后台更新。上面的第一行代码允许您将自己的事件处理程序(DataGridView1\u CurrentCellDirtyStateChanged
)附加到CurrentCellDirtyStateChanged
)事件。因此,每当单元格变脏时,幕后将调用基本级别的事件,然后调用您的方法。如果没有该行,将不会调用您的方法。+=
操作符将方法附加到事件的调用链
例如,添加以下处理程序:
this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_Example1;
// this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_Example2;
this.dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_Example3;
private void DataGridView1_Example1(object sender, EventArgs e)
{
Console.WriteLine("Example 1");
}
private void DataGridView1_Example2(object sender, EventArgs e)
{
Console.WriteLine("Example 2");
}
private void DataGridView1_Example3(object sender, EventArgs e)
{
Console.WriteLine("Example 3");
}
当脏状态更改时,您将看到以下输出。请注意,已排除第二个事件处理程序:
// Example 1
// Example 3
车里有个小问题。它适用于鼠标点击。但是,如果使用空格键切换复选框,则如果不先手动切换当前单元格,则无法再次切换复选框。只要做一点小改动,它就可以工作了:
private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.dataGridView1.IsCurrentCellDirty && this.dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
{
this.dataGridView1.EndEdit();
DataGridViewCell currentCell = this.dataGridView1.CurrentCell;
this.dataGridView1.CurrentCell = null;
this.dataGridView1.CurrentCell = currentCell;
}
}
我使用了您的代码,它工作正常。但我不理解{this.dataGridView1.CurrentCellDirtyStateChanged+=dataGridView1\u CurrentCellDirtyStateChanged;}