How to properly check DataGridViewRow data when validating?

I have a simple edit routine for my DataGridView. It basically loops thru each row checking each column to make sure there is data in it. However, if a column has empty data and it's a date or numeric field, I get the following error:

    "Conversion from type 'DBNull' to type 'Integer' is not valid".

I'm pretty sure I need to do some kind of conversion but not sure how to syntactically set it up. Here is my edit routine below.

        Private Function EditsPassed() As Boolean
        Dim blnPassed As Boolean = True

            For Each row As DataGridViewRow In dgvTrans.Rows
                If IsDBNull(row.Cells(3).Value) Then
                    blnPassed = False
                ElseIf IsDBNull(row.Cells(4).Value) Then
                    blnPassed = False
                ElseIf IsDBNull(row.Cells(5).Value) Then
                    blnPassed = False
                ElseIf IsDBNull(row.Cells(6).Value) Then
                    blnPassed = False
                ElseIf IsDBNull(row.Cells(7).Value) Then
                    blnPassed = False
                End If

        Catch ex As Exception
            Dim strErr As String = "frmTransactions/EditsPassed() - " & ex.Message
            MessageBox.Show(strErr, "User Notification", MessageBoxButtons.OK, MessageBoxIcon.Error)
            blnPassed = False
        End Try

        Return blnPassed
    End Function
Who is Participating?
Jacques Bourgeois (James Burger)Connect With a Mentor PresidentCommented:
Is DBNull is to be used from data that comes directly from a database.

Once it is in the grid, the concept of null is different. You should then check for Nothing instead.

If row.Cells(3).Value Is Nothing then btnPassed = False.

And a little suggestion to make the method faster. If I understand correctly, you want to return False if any of the cells is empty. In such a case, as soon as you hit one empty cell, instead of setting blnPassed and continue looping, simply Return False. The routine will return right there with the proper value.

My line would then become

If row.Cells(3).Value Is Nothing then Return False
BlakeMcKennaAuthor Commented:

Thanks for the answer. As far as returning False as soon as the condition is met, I usually do that kind of logic but just forgot here. Thanks for pointing that out!

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.