datagridview单元格编辑状态下按回车
我们知道由于DataGridView的单元格DataGridCell处于编辑的时候,当你按Enter键,那么DataGridView是不会激发KewPress/KeyDown/KeyUp这些事件的,因为这个时候的DataGridView是一个容器。
在网上找到这篇文章并翻译成VB.NET代码
Namespace WindowsFormsApplication Public NotInheritable Class MyDataGridView Inherits DataGridView Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean If keyData = Keys.Enter Then Me.OnKeyPress(New KeyPressEventArgs("r"c)) ' 下面是对的() ' SendKeys.Send("{r}") Return True Else Return MyBase.ProcessCmdKey(msg, keyData) End If End Function End ClassEnd Namespace Private Sub myDataGridView1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) If e.KeyChar = "r"c Then Dim dgv As DataGridView = TryCast(sender, DataGridView) Dim cell As DataGridViewCell = dgv.CurrentCell If cell.IsInEditMode Then '限制单元格只能输入test If cell.EditedFormattedValue IsNot Nothing AndAlso cell.EditedFormattedValue.ToString() <> "test" Then MessageBox.Show("输入内容不合格") Else dgv.CurrentCell = dgv(cell.ColumnIndex, cell.RowIndex + 1) End If End If End If End Sub Private Sub myDataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Dim dgv As DataGridView = TryCast(sender, DataGridView) Dim cell As DataGridViewCell = dgv(e.ColumnIndex, e.RowIndex) If True Then '限制单元格只能输入test If cell.EditedFormattedValue IsNot Nothing AndAlso cell.EditedFormattedValue.ToString() <> "test" Then MessageBox.Show("输入内容不合格") dgv.CurrentCell = cell Else dgv.CurrentCell = dgv(cell.ColumnIndex, cell.RowIndex + 1) End If End If End SubProtected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean If keyData = System.Windows.Forms.Keys.Enter Then End If Return MyBase.ProcessCmdKey(msg, keyData)End FunctionPrivate Sub dataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) cotrol = New TextBox() cotrol = DirectCast(e.Control, TextBox) cotrol.KeyPress += New KeyPressEventHandler(AddressOf cotrol_KeyPress)End SubPrivate Sub cotrol_KeyPress(sender As Object, e As KeyPressEventArgs)End Sub
[解决办法]