我一直在寻找某种机制,该机制允许检测 a 的任何时候DataGridViewRow
发生DataGridView
变化,一旦DataGridView
没有直接的方法来做到这一点。我已经做了这个实现
public partial class MyDatagrid : DataGridView
{
public event EventHandler<RowChangingArgs> RowUpdating;
public MyDatagrid()
{
InitializeComponent();
this.CellBeginEdit += OnCellBeginEdit;
}
private DataGridViewRow oldRow;
private int currentRow;
private void OnCellBeginEdit(object sender, DataGridViewCellCancelEventArgs args)
{
if(oldRow == null || currentRow != args.RowIndex)
{
if(currentRow != args.RowIndex && oldRow != null)
{
var newRow = this.Rows[args.RowIndex];
foreach (var cell in oldRow.Cells)
{
foreach (var cell1 in newRow.Cells.Cast<object>().Where(cell1 => !cell.Equals(cell1)))
{
if(RowUpdating!= null)
RowUpdating.Invoke(this, new RowChangingArgs { OldRow = oldRow, NewRow = newRow});
oldRow.Dispose();
goto called;
}
}
}
called:
oldRow = this.Rows[args.RowIndex].Clone() as DataGridViewRow;
currentRow = args.RowIndex;
}
}
public class RowChangingArgs : EventArgs
{
public DataGridViewRow OldRow { get; set; }
public DataGridViewRow NewRow { get; set; }
}
}
示例:
用户编辑第 1 行和第 1 列,通过编辑同一行的 n 列来保持。用户开始编辑其他行。带有第 1 行旧内容和第 1 行新内容的触发事件。
这是这样做的好方法,还是我错过了什么?