I have a function that imports an Excel sheet into a SQL database. This function works except ONE line.

If sheetContent.Range("A" & exRow).Value2.ToString.Length < 1 Then
     Exit For
End If

The rest of this function works great, and it uses lines of code that are VERY similar to that one.

The error I'm getting is:

System.NullReferenceException: Object reference is not set to an instance of an object.


Anyone have any ideas? All help is MUCH appreciated!

can you please try to check for null value before taking the length

something like

If isnull(sheetContent.Range("A" & exRow).Value2.ToString.Length)

isnull() for some reason is not an option for me. I should have posted this earlier: I'm using VS2008 .net framework 3.5

I did try:

If String.IsNullOrEmpty(sheetContent.Range("A" & exRow).Value2.ToString) Then
    Exit For
End If

But it did not like this either. I received the same error message.

I'm at a loss on this. That line is looking for a null, yet it throws a NullReferenceException? Any ideas? Again, all help is MUCH appreciated!

I figured it out. When using .ToString , if the object you are trying to convert is null, the method returns null. However, the Convert.ToString() method is smart, and if the object you're referencing is null, then it returns an empty string. Problem solved.

Thank you for your post - it got me thinking in a different light.

If Convert.ToString(sheetContent.Range("A" & exRow).Value2) = "" Then
     Exit For
End If

Edited 5 Years Ago by bklynman01: solved

This question has already been answered. Start a new discussion instead.