Link to home
Start Free TrialLog in
Avatar of PNRT
PNRT

asked on

VB.Net Datagridview - Return to edited cell

Hi Experts.  On CeIlEndEdit I am trying to check the number of digits in the cell and if incorrect get the focus back to the cell so that the next key pressed appears in the cell to be corrected.   It works sometimes but most times the next key pressed appears in the cell that was selected after leaving the first cell.   Any help would be appreciated.

Relevantcell = DataGridView2.CurrentCell
        If DataGridView2.CurrentCell.ColumnIndex = 2 Then
            If Relevantcell.FormattedValue.ToString.Length < 10 Then
                MsgBox("The number is too short")
                DataGridView2.CurrentCell = Relevantcell
                DataGridView2.BeginEdit(True)
                Exit Sub
            End If
        End If
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PNRT
PNRT

ASKER

Thanks for the reply.  I changed the code to the following.  The messagebox appears, then the focus moves to the correct cell ready for editing but the next key stroke then appears in the cell that was clicked after the incorrect data was added.   Also, if I manually return to the cell, the error checking does not work twice.  Thanks again for the reply

Dim Relevantcell As DataGridViewCell

Relevantcell = CType(sender, DataGridView).Rows(e.RowIndex).Cells(e.ColumnIndex)
   If DataGridView2.CurrentCell.ColumnIndex = 2 Then
        If Relevantcell.FormattedValue.ToString.Length < 10 Then
             MsgBox("The number is too short")
             DataGridView2.CurrentCell = Relevantcell
             DataGridView2.BeginEdit(True)
             Exit Sub
         End If
   End If
Actually CodeCruiser was correct - for your task you need validating event and setting e.Cancel=True to continue editing same cell