【问题标题】:Create a new line in a cell of datagridview when User press ENTER当用户按 ENTER 时,在 datagridview 的单元格中创建一个新行
【发布时间】:2019-07-02 19:07:25
【问题描述】:

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

【问题讨论】:

  • 设置:DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.TrueDataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells 并使用SHIFT+ENTER 创建新行。
  • 如果你不喜欢SHFT+ENTER,你需要创建一个自定义的DataGridViewTextBoxEditingControl Class
  • 我刚刚尝试了你在第一篇文章中所说的,但我不知道为什么当我按 shift+ 输入新行时,单元格中出现了焦点,但焦点在另一个单元格中传递...跨度>
  • 查看您是否有一些以前尝试过的代码妨碍了您。尝试使用新的 DataGridView,仅使用第一条评论中显示的两行。按F2 或单击单元格两次进入编辑,然后按Shift+Enter 插入新行。
  • 嗨,吉姆,我找到了问题所在。我的表单打开了 keypreview,我处理了 ENTER 按键到 sendkeys TAB 以移动到表单中的下一个控件。我不想失去这个功能。我认为唯一的解决方案是实现自定义 DataGridViewTextBoxEditingControl 类。我从不使用它,我需要研究它。Tnx!

标签: vb.net datagridview cell enter


【解决方案1】:

我已经阅读了您所说的帖子。 转换我得到的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

但不工作。怎么了?

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2012-01-06
    相关资源
    最近更新 更多