Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading a empty cell, gives object reference error

Tags:

c#

linq

epplus

When I read a cell by doing Worksheets.Cells[2,5].value.ToString();

I get a error "System.NullReferenceException: Object reference not set to an instance of an object."

What would be a good way to check for null and then assign the value, without having to have a "if" statement.

like image 873
sansid Avatar asked Aug 15 '12 04:08

sansid


People also ask

Why does it say null object reference?

So, a reference is what a variable of a reference type contains. These variables can point to “nothing”, though, and that's what we call a null reference: a reference that doesn't point to any object. When you try to call a method or another member on the said variable, you got the NullReferenceException.

What is object reference not set to an instance?

The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.


1 Answers

 string strValue = Worksheets.Cells[2,5].value==null ? string.Empty : Worksheets.Cells[2,5].value.ToString();

or

object objValue = Worksheets.Cells[2,5].value ?? string.Empty
like image 58
horgh Avatar answered Oct 21 '22 12:10

horgh