DataGridView在单元格编辑结束后如何设置焦点

3

我使用了CellEndEdit事件,在编辑单元格的值后按Enter键,然后单元格焦点会向下移动。

我希望焦点返回到我编辑值的原始单元格。

我尝试了很多方法,但都失败了。

Private Sub DataGridVie1_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridVie1.CellEndEdit
   '...
   '....editing codes here...to input and validate values...
   '...
   '...
   '...before the End If of the procedure I put this values
   DataGridVie1.Rows(e.RowIndex).Cells(e.ColumnIndex).Selected = True
   DataGridVie1.CurrentCell = DataGridVie1.Rows(e.RowIndex).Cells(e.ColumnIndex)
   'DataGridVie1.BeginEdit(False) '''DID NOT apply this because it cause to edit again.
End If

当编辑或按下 ENTER 键后,焦点回到原始单元格时,我不知道真正的代码。

因为每次按下 ENTER 键,它直接跳到下一个单元格。

重新将焦点定位到原始编辑单元格的代码是什么?

我知道 EditingControlShowing 方法,但我认为我不必使用该方法来获得所需的结果。

2个回答

7
试试这个:定义3个变量。一个用于记忆是否进行了编辑操作,另外两个用于存储最后一个被编辑单元格的行和列索引。
Private flag_cell_edited As Boolean
Private currentRow As Integer
Private currentColumn As Integer

当编辑操作发生时,您会在 CellEndEdit 事件处理程序中存储已编辑单元格的坐标,并将您的标志设置为true:

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
End Sub 

然后在 SelectionChanged 事件处理程序中,您可以使用 currentRowcurrentColumn 变量将 DataGridViewCurrentCell 属性设置为最后编辑的单元格,以撤消默认的单元格焦点更改:

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

我不需要再思考这个方法,因为你已经提供了。谢谢你和Stack Overflow。 - XXXXXXXXXXXXXX

0

Andrea的想法,但使用DataGridViewCell来处理事情:

Private LastCell As DataGridViewCell = Nothing

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

Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
    If LastCell IsNot Nothing Then
        DataGridView.CurrentCell = LastCell
        LastCell = Nothing
    End If
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接