确定 DataGridView 中的单元格何时发生更改,但仅在退出编辑模式后



我已经阅读了几篇关于这个主题的文章,但似乎都不适合我的确切情况。我基本上想在用户进行任何更改后执行一些代码以从 DataGridView 单元格复制数据。但具体来说,我只想在用户完成单元格编辑后获取值,并且单元格值实际上不同(例如,用户没有取消编辑(。我正在寻找的行为与仅在用户实际更新单元格公式后 Excel 更新单元格公式的方式相同。到目前为止,这是我开始的代码:

private void MyDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// Exit this event procedure if no rows have been added to the DataGridView yet (during program initialization)
if (e.RowIndex < 0)
{
return;
}
// Get an object reference to the current Value cell
DataGridViewCell cell = (DataGridViewCell)MyDataGridView.Rows[e.RowIndex].Cells[1];
// Do other stuff with the cell data here   
}
private void MyDataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
// Force the CellValueChanged event to trigger for the control if the current cell's value has changed
if (MyDataGridView.IsCurrentCellDirty)
{
MyDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}

它的工作原理是,每次进行编辑时都会触发 CellValueChanged 事件。但是,每次用户在编辑模式下键入键时都会触发该事件,我只想在用户退出编辑模式后触发一次(并假设进行了更改并且未取消(。解决这个问题的最佳方法是什么?我还查看了CellEndEdit事件,这似乎让我更接近了一点,但我仍然无法确定编辑是已提交还是已取消。对此的最佳/推荐方法是什么?

好的,大家,我找到了一个简单的问题解决方案。要使其正常工作,您需要做的就是使用 CellBeginEdit 和 CellEndEdit 事件。我创建了一个名为 CellValue 的全局变量,它设置为 CellBeginEdit 事件中单元格的内容。稍后,将根据 CellEndEdit 事件中单元格的当前值检查此存储的值。如果它们不同,那么我可以执行处理单元格中新更改的数据所需的代码。

我知道这种方法可能不适用于每种情况,但只是想我会为遇到相同问题的其他任何人分享。下面是一个快速代码示例,说明了我所做的事情:

// Temporarily holds the value of a cell in the DataGridView once a cell has begun to be edited.
// The value in this variable is then compared to the value of the cell after the edit is complete to see if the data chagned before updating the controlParameters object
object CellValue;
private void MyDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
// Set this variable to the current cell's value to compare later to see if it's contents have changed
this.CellValue = MyDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
}
private void MyDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Exit this event procedure if no rows have been added to the DataGridView yet (during program initialization)
if (e.RowIndex < 0)
{
return;
}
// Proceed only if the value in the current cell has been changed since it went into edit mode
if (this.CellValue != MyDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value)
{
// Do your cell data manipulation here
}
}

最新更新