Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a datagridview column that I wish to prevent the user from leaving the cell blank or input negative numbers. I've found that when I change the order of the if then statements to have the blank validation check first the code works, but not for the negative validation and vice-versa. So why is it that the code is only working for the first if statement and ignoring the second? I greatly appreciate any help or suggestions anyone can give on this. :)

VB
If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellData As Integer

        If (Int32.TryParse(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value, cellData)) Then
            If cellData < 0 Then
                MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Name"
                Exit Sub ' Again this a default value I want supplied back to the datagridivewcell
            End If
        Else
            Dim testData As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
                If (String.IsNullOrEmpty(testData)) Then
                MessageBox.Show("Cannot Be Empty")
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Name" ' This is a default value that I want to supply after the message box
            End If
        End If

    End If
Posted

1 solution

If the cell has to be checked for both the conditions try the following code:

VB
If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellData As Integer

        IF Not DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value is DBNull.Value Then
            If (Int32.TryParse(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value, cellData)) Then
                If cellData < 0 Then
                    MessageBox.Show("Negative Numbers Not Allowed")
                    DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Name"
                    Exit Sub
                End If
            End If
            If (String.IsNullOrEmpty(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)) Then
                MessageBox.Show("Cannot Be Empty")
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Name"
                Exit Sub '
            End If
        Else
            MessageBox.Show("Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Name"
            Exit Sub
        End If
End If
 
Share this answer
 
Comments
CAS1224 3-Jul-13 12:05pm    
You're a life saver! Thanks so much for your help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900