2009-01-08 68 views
8

我在我的WinForms应用程序中使用DataGridView。我的主要目标是使Enter键不移动到网格中的下一行。我仍然希望回车键验证并结束编辑模式。我可以让DataGridView.EndEdit触发CellValidating事件吗?

我发现this FAQ entry和子类DataGridView重写ProcessDialogKey()。如果按下的键是Enter,我调用EndEdit(),否则我调用base.ProcessDialogKey()。

它的效果很好,除了CellValidating事件没有被触发。

目前,我只是在我调用EndEdit之前手动调用我的验证逻辑,但似乎我失去了一些东西。

我想我可以打电话给OnCellValidating,但后来我担心我错过了其他一些事件。我真正想要的是EndEdit()的某种风格,就像在添加禁用的网格的最后一行上按Enter键一样。

回答

11

直到您更改CurrentCell时才会调用CellValidating。所以我对这个问题的看法是改变CurrentCell,然后切换回当前的。

protected override bool ProcessDialogKey(Keys keyData) 
    { 
     if (keyData == Keys.Enter) 
     { 
      DataGridViewCell currentCell = CurrentCell; 
      EndEdit(); 
      CurrentCell = null; 
      CurrentCell = currentCell; 
      return true; 
     } 
     return base.ProcessDialogKey(keyData); 
    } 
0

不,但您可以手动触发CellValidating事件。只需创建适当的参数。所有事件都是使用Observer Pattern的类,它们与其他方法没有区别。如果这不起作用,您可以在单元格上创建一个KeyPress事件并模拟单元格上的Enter键,但这可能会与用户界面混淆,只需将克拉放回原位即可。

+0

不幸的是,EventArgs类的CellValidating事件不具有公共构造函数。 – 2009-05-05 17:04:59

+0

无论如何,你可以使用反射来访问构造函数,但在单元测试之外看起来相当粗糙。 – 2014-02-07 13:58:06

1

感谢您的解决方案。 我的版本与你的版本略有不同,因为当我移动到另一个单元格时,并且我的代码在单元验证事件中返回e.cancel = false时,将产生一个错误,它说:“操作没有成功,因为该程序不能提交或退出单元值更改“。所以我把尝试赶上来克服这个问题。

这是我的代码:

Protected Overrides Function ProcessDialogKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean 

    Dim key As Keys = (keyData And Keys.KeyCode) 

    If key = Keys.Enter Then 
     If MyBase.CurrentCell.ColumnIndex = 1 Then 
      Dim iRow As Integer = MyBase.CurrentCell.RowIndex 

      MyBase.EndEdit() 
      Try 
       MyBase.CurrentCell = Nothing 
       MyBase.CurrentCell = MyBase.Rows(iRow).Cells(1) 
       frmFilter.cmdOk_Click(Me, New EventArgs) 
      Catch ex As Exception 
      End Try 

      Return True 
     End If 
    End If 

    Return MyBase.ProcessDialogKey(keyData) 
End Function 
2

如果你的DataGridView的DataSource是BindingSouce,做到这一点(把这个在您的Key processing events):

bds.EndEdit(); 

如果你的DataGridView的数据源是数据表:

this.BindingContext[dgv.DataSource].EndCurrentEdit(); 
5

如果单元格处于编辑模式,JJO的代码将会崩溃。下面避免了验证异常:

DataGridViewCell currentCell = AttachedGrid.CurrentCell; 
     try 
     {    
      AttachedGrid.EndEdit(); 
      AttachedGrid.CurrentCell = null; 
      AttachedGrid.CurrentCell = currentCell; 
     } 
     catch 
     { 
      AttachedGrid.CurrentCell = currentCell; 
      AttachedGrid.CurrentCell.Selected = true; 
     } 

来源:Kennet Harris's answer here