Checking value of empty cell in dgrid gives error

dotolee

Member
Joined
Nov 30, 2004
Messages
20
Programming Experience
10+
I'm looping through all cells in a selected row, trying to check for emtpy (either null or just empty string), but i'm getting the following error:

System.NullReferenceException was unhandled

My code looks like:
VB.NET:
           For Each cell As DataGridViewCell In row.Cells
                If ignoreRow = False Then
                    Exit For
                End If
                [B]If Not String.IsNullOrEmpty(cell.Value.ToString) Or Not (IsNothing(cell.Value)) Then[/B]                    Debug.Print(cell.Value.ToString)
                    ignoreRow = False
                End If
            Next

The bolded line is where it fails. Previously, i had just the first part of the if statement, but in playing around, i tried to also add the "Not (IsNothing(cell.Value)) " to see if it would help.
Any help would be appreciated!
Thank you.
 
Rather than putting code in via trial and error, take a step back and thing about the order you do things and the logical tests youre applying. Review this code:

VB.NET:
Dim x as Object = Nothing

If x.ToString() ="Something" Or Not x Is Nothing Then 
 'code
End If

Will it crash? Definitely. Why? Because things are evaluated from left to right so the x.ToString() is called first.
ALSO, think about your operators.. Or and And are full evaluation, OrElse and AndAlso are short circuit evaluators (OrElse/AndAlso dont bother evaluating the right if the left is true/false respectively)

Take a few moments to re-read your code and have a think about the order it's doing stuff and why youre getting a null reference (==youre accessing a property or method on an object that is Nothing)
 
Back
Top