0
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. :)

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
1

1 Answers

1
votes
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 = "Vendor 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 = "Vendor Name"
                Exit Sub '
            End If
        Else
            MessageBox.Show("Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Vendor Name"
            Exit Sub
        End If
    End If