Dear Sir,

How to combine these two conditions in one section

Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating

'condition 1       

        ' check given value is numeric or charactr type
        If e.ColumnIndex = 3 Then
            If Not IsNumeric(e.FormattedValue) Then
                DataGridView1.Rows(e.RowIndex).ErrorText = " must be a numeric value"
                MsgBox("Must be a numeric value")
                DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(3).Value = Nothing
                e.Cancel = True
            End If
        End If

'condition 2
        ' check given value is greater than 0 or not 
        If e.ColumnIndex = 3 Then
            If (e.FormattedValue.ToString = "0") Then
                e.Cancel = True
                MsgBox(" must be greater than 0")
            End If
        End If
    End Sub

Recommended Answers

All 2 Replies

hi i am a beginner but will still try to slove this. i have posted the solution below but not tested yet. I hope it helps

If e.ColumnIndex = 3 Then
            If Not IsNumeric(e.FormattedValue) And (e.FormattedValue.ToString = "0") Then
                DataGridView1.Rows(e.RowIndex).ErrorText = " must be a numeric value"
                MsgBox("Must be a numeric value")
                DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(3).Value = Nothing
                e.Cancel = True
                MsgBox(" must be greater than 0")

            End If
        End If

another way is to use if-else structure:

If e.ColumnIndex = 3 Then 
        If Not IsNumeric(e.FormattedValue) Then
               DataGridView1.Rows(e.RowIndex).ErrorText = " must be a numeric value"
                MsgBox("Must be a numeric value")
                DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(3).Value = Nothing
                e.Cancel = True
        ElseIf (e.FormattedValue.ToString = "0") Then
                e.Cancel = True
                MsgBox(" must be greater than 0")            
        End If
End If

Some situations dont lend themselves to a combined condition, an if-else structure will test each condition from teh top down until it meets one so be careful abou thte order of your conditions

commented: Got there before I could answer! Good solution +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.