【问题标题】:DataGridView SetFocus does not move to next rowDataGridView SetFocus 不移动到下一行
【发布时间】:2016-01-02 20:57:22
【问题描述】:

我在一个有 4 列的表单中使用了 DataGridView 功能:项目代码、描述、数量、价格。我希望在将项目代码插入单元格时,焦点应该移到同一行的第三个单元格上,即第三列(数量)。直到这里它工作正常,因为我提到了这个链接。

DataGridView SetFocus after CellEndEdit

现在的问题是它卡在第三个单元格上,当我按下回车键时它没有移动到下一行第一列(项目代码)。我的代码是

Private flag_cell_edited As Boolean
Private currentRow As Integer
Private currentColumn As Integer 


Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        flag_cell_edited = True
        currentColumn = e.ColumnIndex
        currentRow = e.RowIndex
        MsgBox(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)

End Sub


Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
        If flag_cell_edited Then
                DataGridView1.CurrentCell = DataGridView1.Rows(currentRow).Cells(2)
                flag_cell_edited = False
        End If
End Sub

我已经使用MsgBox查看插入单元格的数据,以便以后可以将其存储到数据库中。

【问题讨论】:

  • 开始删除那个 MsgBox。这条线会干扰控件之间的正常焦点流动。使用简单的 Console.WriteLine 在调试窗口中观察结果。
  • 我删除了该行,但仍然无法正常工作。当第一次焦点移动到第三个单元格(即数量)并且我插入一些值并且 HIT 进入所以没有任何反应并且焦点保持在同一个单元格中但是当我第二次进入时它移动到下一行第 3 列(即数量)

标签: vb.net datagridview


【解决方案1】:

当您在第三个单元格上按 Enter 键时,您会收到 CellEndEdit 事件,就像您在第一个单元格中结束编辑时一样。只有在第一个单元格时才需要触发第三个单元格的移动

Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

    if e.ColumnIndex = 0 Then
        flag_cell_edited = True
        currentColumn = e.ColumnIndex
        currentRow = e.RowIndex
    Else
        flag_cell_edited = False
    End If
End Sub


Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
    If flag_cell_edited Then
        DataGridView1.CurrentCell = DataGridView1.Rows(currentRow).Cells(0)
        flag_cell_edited = False
    End If
End Sub

【讨论】:

  • 谢谢史蒂夫,它有点工作,但是当我在第三个单元格上按 Enter 键时它移动到下一行第三个单元格,它应该移动到下一行第一个单元格。
  • 只需更改 2 in 0
  • 我用名称 flag_cell_edit1 初始化了另一个变量,并在两个事件中引入了 if 循环,就像 flag_cell_edit 一样,它起作用了。这是我在 SelectionChanged 事件中所做的一些更改: % If flag_cell_edited1 Then DataGridView1.CurrentCell = DataGridView1.Rows(currentRow + 1).Cells(0) flag_cell_edited1 = False End If % 非常感谢@steve 的帮助,我编辑了你的代码,它工作!谢谢大佬!
猜你喜欢
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多