DataGridview with the Validating method being circumvented by Tab keypress

Joined
Mar 18, 2014
Messages
18
Location
Devon, UK
Programming Experience
3-5
Hi Guys,

Am having a problem with the Datagridview control and the validation process. As an example, try this :

Have a small form, with DataGridview control with 2 columns added.
In the first column(txtCol1 in code below) I want to only to be able to accept numbers. So in the Validating method I have used the Double.TryParse which works fine. If it is a number then the cell pointer can leave the cell and move to the next cell.
If not a number an error message gets displayed and the first column stays the current cell.

Now this all works fine... if you add text (not a number) to the first column and click into the 2nd column the code validates this correctly and prevents you entering into the 2nd column as it should.
The problem I have is that when entering data into a datagridview control people are used to hitting the Tab key to move from cell to cell.

Hitting the Tab key does something unexpected. It executes the txtCol1_Validating method as it should....shows the error... all good... but then it runs the txtCol1_Validating code again clears the cell of its contents...displays the error message a second time...replaces the contents and then puts the cell pointer into the 2nd column!! - Not what I expected at all.

What am I missing?


Public Class Form1
    Private WithEvents txtCol1 As New DataGridViewTextBoxEditingControl
    Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If DataGridView1.CurrentCell.ColumnIndex = 0 Then
            txtCol1 = CType(e.Control, DataGridViewTextBoxEditingControl)
        Else
            txtCol1 = Nothing
        End If
    End Sub
    Private Sub txtCol1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles txtCol1.Validating
        If Not Double.TryParse(Me.txtCol1.Text, 0) Then
            MessageBox.Show("Not a number")
            e.Cancel = True
        End If
    End Sub
End Class


Many thanks in advance for any help you can provide.

DG.
 
Ahh... its ok... found the problem.... I think I was doing things the hard way - here's what I needed :

Private  Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
     If DataGridView1.CurrentCell.ColumnIndex = 0 Then
          If Not Double.TryParse(Me.txtCol1.Text, 0) Then
               MessageBox.Show("Not a number")
               e.Cancel = True
          End If
     End If
End Sub
 
Back
Top