用户按下ENTER键时,在datagridview单元格中创建新行

时间:2019-02-08 14:06:32

标签: vb.net datagridview cell enter

在vb.net中创建的项目中,我有一个datagridview,用户可以在其中直接输入数据。 列是数量,描述,价格和总计。 “数量”和“价格”列仅允许输入数字和逗号,计算得出总列。 我希望当用户编辑描述单元格时,如果按ENTER,则创建新行(crlf)。 因为我没有在互联网上找到任何有用的例子,您能帮我吗?

1 个答案:

答案 0 :(得分:0)

我已经阅读了您所说的信息。 转换我获得的c#代码形式

Public Class CustomDataGridViewTextBoxEditingControl
Inherits DataGridViewTextBoxEditingControl

Public Overrides Function EditingControlWantsInputKey(ByVal keyData As Keys, ByVal dataGridViewWantsInputKey As Boolean) As Boolean
    Select Case keyData And Keys.KeyCode
        Case Keys.Enter
            Return True
        Case Else
    End Select
    Return MyBase.EditingControlWantsInputKey(keyData, dataGridViewWantsInputKey)
End Function
Protected Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
    Select Case e.KeyCode And Keys.KeyCode
        Case Keys.Enter
            Dim oldSelectionStart As Integer = Me.SelectionStart
            Dim currentText As String = Me.Text
            Me.Text = String.Format("{0}{1}{2}", currentText.Substring(0, Me.SelectionStart), Environment.NewLine, currentText.Substring(Me.SelectionStart + Me.SelectionLength))
            Me.SelectionStart = oldSelectionStart + Environment.NewLine.Length
        Case Else
    End Select

    MyBase.OnKeyDown(e)
End Sub
End Class
Public Class CustomDataGridViewTextBoxCell
Inherits DataGridViewTextBoxCell
Public Overrides ReadOnly Property EditType As Type
    Get
        Return GetType(CustomDataGridViewTextBoxEditingControl)
    End Get
End Property
End Class

然后,以包含datagridview(测试项目!)的形式添加

Private Sub Form3_Load(sender As System.Object, e As System.EventArgs) Handles 
MyBase.Load

    Dim col As DataGridViewColumn = Me.DataGridView2.Columns(2)
    col.CellTemplate = New CustomDataGridViewTextBoxCell

End Sub

但不起作用。怎么了?