• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 160
  • Last Modified:

How do I validate a value in a databound DataViewGrid in vb.net?

I am trying to trap entry errors in a databound DataGridView.  I am trying to stop the user from entering non-numeric values in a numeric field.  I'm able to trap the error in the CellValidating event.  But, it still generates a DataGridView error for a System.Format exception.  How do a trap the error and make sure it doesn't get to the CellValueChanged event?  I just want a simple solution.  I seem to be running around in circles.
Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
        Dim sUnitOld As String
        Dim sUnitNew As String
 
        'UNIT
        If (DataGridView1.Columns(e.ColumnIndex).Name = "UNIT") Then
            sUnitOld = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value.ToString
            sUnitNew = e.FormattedValue.ToString
            bUnitVerified = True
            If Not IsNumeric(sUnitNew) Then
                bUnitVerified = False
                MsgBox("Unit value '" & sUnitNew & "' is not numeric. Please correct before saving.", , "Invalid Unit")
                DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = sUnitOld
                Exit Sub
            End If
 
        End If
 
   End Sub

Open in new window

0
tjlemahieu
Asked:
tjlemahieu
1 Solution
 
jpaulinoCommented:
You can use the DataError event.
Example:

    Private Sub DataGridView1_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
        If e.ColumnIndex = 0 Then
            MessageBox.Show(e.Exception.Message)
            e.Cancel = True ' Disables the system error message
        End If
    End Sub

Open in new window

0
 
tjlemahieuAuthor Commented:
That worked great!  Thanks.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now