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.