0

I am wondering if there's a way to check if an object exists before referencing at all. Not just check if it is null because that isn't working either. I am using EPPlus package to read excel files and when it gets to an index that does not have any value data in it, it sends an exception.

private DataTable WorksheetToDataTable(string tableName)
{
    excelSheet = excelWorkbook.Worksheets[tableName];
    DataTable dt = new DataTable();
    try
    {
        int totalRows = excelSheet.Dimension.End.Row;
        int totalCols = excelSheet.Dimension.End.Column;
        for (int j = 1; j <= totalCols; j++)
        {

            dt.Columns.Add();
            for (int i = 1; i <= totalRows; i++)
            {
                if (j == 1)
                {
                    dt.Rows.Add();
                }
                try
                {
                    dt.Rows[i - 1][j - 1] = excelSheet.Cells[i, j].Value.ToString();
                    //dt.Rows[i - 1][j - 1] = Object.ReferenceEquals(null, excelSheet.Cells[i, j].Value.ToString()) ? "" : excelSheet.Cells[i, j].Value.ToString();
                }
                catch
                {
                    dt.Rows[i - 1][j - 1] = "";
                }
            }
        }
        return dt;
    }
    catch
    {
        MessageBox.Show("Error: Referenced Excel Table is empty, or indexed improperly! Check Excel formatting.", "Error");
        return dt;
    }
}

So you can see I've tried checking if the excelSheet.Cells[i, j].Value.ToString() was null before and it sends the same exception caught in the try/catch I have above. I have to parse a lot of cells and a lot of them will be completely empty, which adds a lot of

Exception thrown: 'System.NullReferenceException' in BBSApp.exe

to the output console. Is there a way to check if the object exists before I call the object to even check if it is null without the try/catch?

if(excelSheet.Cells[i, j].Value.ToString() != null)

Simply checking if it is null as shown above sends the same exception because it does not exist in the first place.

Felipe Pincheira
  • 442
  • 1
  • 6
  • 21
Mike H
  • 387
  • 9
  • 25
  • 8
    "Simply checking if it is null as shown above sends the same exception because it does not exist in the first place." No, that's checking if the *result of calling `ToString()`* is null. You should check whether `excelScheet` is null (seems unlikely), or if `excelSheet.Cells[i, j]` is null or if `excelSheet.Cells[i, j].Value` is null. – Jon Skeet Jul 27 '17 at 20:40

3 Answers3

5

Try this:

if(excelSheet.Cells[i, j].Value != null)

You're checking to see the Value property is null. The null reference exception occurs because you are trying call the method ToString() on a null object.

Alternatively, you can use the null access operator:

if(excelSheet.Cells[i, j]?.Value?.ToString() != null)
Michael
  • 1,556
  • 13
  • 25
3

According to the documentation, you should use IsEmpty.

If the specified Range object is empty, returns the value Empty (use the IsEmpty function to test for this case). If the Range object contains more than one cell, returns an array of values (use the IsArray function to test for this case).

Example:

if (!excelSheet.Cells[i, j].Value.IsEmpty)
{
    dt.Rows[i - 1][j - 1] = excelSheet.Cells[i, j].Value.ToString();
}
John Wu
  • 50,556
  • 8
  • 44
  • 80
1

Before accessing the excelSheet field, you can check whether or not the object has been initialised using null-check propagation:

if (excelSheet.Cells[i, j]?.Value != null)
    // Do whatever
Demitrian
  • 3,200
  • 1
  • 24
  • 41