我有一个扩展DataGridView控件的控件。我正在重写ProcessDialyKey事件并抛出我自己的事件,当用户在单元格中键入时,容器表单可以响应。
我发现的问题是,当我从DataGridView的ProcessDialogKey方法中触发“CellEditKeyPress”事件时,我正在编辑的单元格的值尚未更新。
因此,当用户输入'a'时,我的CellEditKeyPress事件会触发,但是当我获取该单元格的值时,该值仍为空字符串。然后用户键入'b',我可以获得的值是'a',依此类推。我的活动总是有效地成为一个关键点。
以下是一些代码来说明:
public class MyDataGridView : DataGridView { public delegate void CellEditKeyPressHandler(Keys keyData, DataGridViewCell currentCell); public event CellEditKeyPressHandler CellEditKeyPress; protected override bool ProcessDialogKey(Keys keyData) { if (CellEditKeyPress != null) { CellEditKeyPress(keyData, this.CurrentCell); } return base.ProcessDialogKey(keyData); } }
...并在我的表格上...连接CellEditKeyPress(在设计师中)
private void myDataGridView1_CellEditKeyPress(Keys keyData, DataGridViewCell currentCell) { myDataGridView1.EndEdit(); if (currentCell.Value != null) { textBox1.Text = currentCell.Value.ToString(); textBox2.Text = currentCell.FormattedValue.ToString(); } myDataGridView1.BeginEdit(false); }
影响是TextBoxes(1& 2)的内容是我正在编辑的单元格内容后面的一个字符。
我尝试过使用ProcessDialogKey方法的顺序无济于事。 (认为它可能需要在触发我的事件之前调用base.ProcessDialogKey方法,但这并没有改变任何东西。)
我还用“this.Validate()”替换了“myDataGridView1.EndEdit()”,试图让控件的值保持最新状态,但没有区别。
有没有办法确保我使用最新的单元格内容?我是否使用了错误的覆盖来实现这一目标?
答案 0 :(得分:2)
这对我有用:
private void myDataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
myDataGridView1.EndEdit();
if (myDataGridView1.CurrentCell.Value != null)
{
textBox1.Text = myDataGridView1.CurrentCell.Value.ToString();
textBox2.Text = myDataGridView1.CurrentCell.FormattedValue.ToString();
}
myDataGridView1.BeginEdit(false);
}
答案 1 :(得分:0)
CellValidating发布此处可以帮助您解决此问题。在更改CurrentCell之前,不会调用CellValidating。所以我解决这个问题的方法就是改变CurrentCell,然后切换回当前的.C。
protected override bool ProcessDialogKey(Keys keyData)
{
DataGridViewCell currentCell = CurrentCell;
EndEdit();
CurrentCell = null;
CurrentCell = currentCell;
if (CellEditKeyPress != null)
{
CellEditKeyPress(keyData, this.CurrentCell);
}
return base.ProcessDialogKey(keyData);
}