Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

vb.net - DataGridView SetFocus after CellEndEdit

I used the CellEndEdit event, after editing the cell value I press the Enter Key, then the cell focus moves down.

I want the focus to go back at the original Cell where I edited the value.

I used many ways, but failed.

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

I don't know the real code when after edit or after a ENTER KEY the focus is back in the original Cell that was edited.

Because everytime I HIT the ENTER KEY, it directly go down to the next Cell.

Whats the code to reposition the focus back to the original Cell edited.

I know the EditingControlShowing method but I don't think I have to used that method to get what I wanted too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this: define 3 variables. One to memorize if an edit operation has been made, the other 2 to store row and column indexes of the last edited cell:

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

When an edit operation occurs you store coordinates of edited cell and set your flag to true inside CellEndEdit event handler:

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 

Then in SelectionChanged event handler you set DataGridView's CurrentCell property to the last edited cell using currentRow and currentColumn variables to undo default cell focus change:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...