【问题标题】:Cursor inside cell datagridview vb.net单元格datagridview vb.net内的光标
【发布时间】:2011-08-16 16:22:26
【问题描述】:

VB.NET DataGridView 控件:

我知道这可能非常简单,但是如何在表单加载时将闪烁的光标放在特定单元格内?

我希望效果有点像当您有一个带有文本框的表单并且正确设置 Tab 键顺序时,第一个文本框将自动获得焦点,您可以立即开始输入。

关于一个相关问题:当​​您在单元格内时,如何让回车键激活表单的接受按钮?

谢谢!

【问题讨论】:

    标签: vb.net datagridview


    【解决方案1】:

    你说得对,将输入光标定位到 DataGridView 中的特定单元格相当容易。将 DataGridView 的 CurrentCell 属性设置为您希望光标所在的单元格,然后调用 DGV 的 BeginEdit 方法。

    以编程方式单击表单的AcceptButton 也很容易(我相信这就是您所说的“激活”的意思)。在表单实例的AcceptButton 上调用PerformClick 方法:

    Me.AcceptButton.PerformClick()
    

    让 DGV 处理 Enter 键有点棘手,尽管表面上看起来可能并非如此。棘手的原因是当您有一个处于编辑模式的 DGV 单元格时,DGV KeyPressPreviewKeyPress 事件不会触发。解决方案是通过扩展标准 DataGridView 创建您自己的 DataGridView,然后覆盖 ProcessCmdKey 函数以触发一个事件,告诉侦听器按下 Enter 键。

    您的扩展 DGV 控件可能如下所示:

    Public Class MyDataGridView
        Inherits System.Windows.Forms.DataGridView
    
        Public Event EnterKeyPressed()
    
        Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
            If keyData = Keys.Enter Then
                RaiseEvent EnterKeyPressed()
            End If
    
            Return MyBase.ProcessCmdKey(msg, keyData)
        End Function
    End Class
    

    因此,假设您使用的是上面的扩展 DGV,您可以按照以下方式做您需要做的事情:

    ' This positions the input cursor in the third column in the third row.
    MyDataGridView1.CurrentCell = MyDataGridView1.Rows(2).Cells(2)
    MyDataGridView1.BeginEdit(False)
    
    
    ' Be sure to wire up the EnterKeyPress event on your shiny new MyDataGridView.
    Private Sub MyDataGridView1_EnterKeyPressed() Handles MyDataGridView1.EnterKeyPressed
       Me.AcceptButton.PerformClick()
    End Sub
    

    【讨论】:

    • @John 不知道为什么,它对我有用。原因可能是您对 DGV 的属性所做的任何更改吗?如果您以新的形式使用新的 DGV(或 MyDataGridView),它是否有效?
    【解决方案2】:

    试试这个代码,它肯定会工作

    dim strRowNumber as string
    
    For Each row As DataGridViewRow In DataGrid.Rows
    
         strRowNumber = DataGrid.Rows.Count - 1
         DataGrid.CurrentCell = DataGrid.Rows(strRowNumber).Cells(1)'Cell(1) is a cell nowhich u want to edit or set focus
         DataGrid.BeginEdit(False)
    Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多