This project has moved and is read-only. For the latest updates, please go here.

check for empty cell

Aug 15, 2012 at 2:22 AM

Hello

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 have to have a "if" statement.

 

 

 

Aug 17, 2012 at 1:52 PM
Edited Aug 17, 2012 at 1:53 PM

Hum, to get a clean code maybe you can use an extension method. Something like this:

 

 

        public static object TryValue<T>(this ExcelRange source)
        {

            if (source.Value != null)
            {
                return (T)source.Value;
            }

            return null;
        }

        public static object TryValueString(this ExcelRange source)
        {

            if (source.Value != null)
            {
                return source.Value.ToString();
            }

            return string.empty;
        }
Aug 19, 2012 at 11:08 AM
suek wrote:

Hello

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 have to have a "if" statement.

 

 

 


This is how I solved it:

string variableA = workSheet.Cells[30, 4].Value ==

null ? string .Empty : workSheet.Cells[30, 4].Value.ToString();

decimal variableB = workSheet.Cells[30, endColumn].Value ==

null ? 0 : Decimal .Parse(workSheet.Cells[30, endColumn].Value.ToString());