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

NullRefernceException was unhandled by user code

Apr 30, 2013 at 6:07 AM
Hi. I am working with EPPLUS in c#. I wrote the below code to read .xlsx file and display the content of a cell.

if (workbook != null)
                ExcelWorksheet sheet = workbook.Worksheets["Sheet1"];
                var firstrow = sheet.Cells["A1:AO1"];
                String[] col = null;
                int i;
                i = 0;
                foreach (var cells in firstrow)
                    var col1 = cells.GetValue<int>();
                    //TextBox1.Text = col1.ToString();
                    col[i] = String.Empty;
                    col[i] = col1.ToString();
                    i = i + 1;
                int j = Convert.ToInt16(TextBox1.Text);
                TextBox2.Text = col[j];
In the above code, at the line
var firstrow = sheet.Cells["A1:AO1"];
I get a NullReferenceException. I am new to C#. Can anyone pls help me?
May 2, 2013 at 9:03 PM
Hi Deepi,

It can be pretty hard to know what the problem is without (ideally) the whole module or project of code to work with and, if at all possible, an output spreadsheet. Given your error, you might want to try ExcelWorksheet sheet = workbook.Worksheets[0]; instead for the one line since the variable "sheet" is probably ending up with a null value.

My first guess is that the problem is probably annoyingly simple: the sheet is actually named "sheet1" rather than "Sheet1" (with a capital). In .NET, most string compares are case sensitive, so it could hit you.