0

I am adding items to string list and i know there is data that exists to insert but i keep getting the null reference error message Object reference not set to an instance of an object.

    public class ExcelRow
        {
            public List<String> lstCells;
            public byte[] rowHash;
            ......
        }
    public class ExcelInfo
        {
            public List<ExcelRow> excelRows;
        }

    public ExcelInfo ReadExcel(OpenFileDialog openFileDialog)
        {
            var _excelFile = new ExcelQueryFactory(openFileDialog.FileName);
            var _info = from c in _excelFile.WorksheetNoHeader() select c;

            ExcelRow excelRow;
            ExcelInfo resp;

            resp = new ExcelInfo();

            foreach (var item in _info)
            {
                excelRow = new ExcelRow();
                excelRow.lstCells.Add(item.ElementAt(0));
                excelRow.lstCells.Add(item.ElementAt(1));
                excelRow.lstCells.Add(item.ElementAt(2));
                excelRow.lstCells.Add(item.ElementAt(3));
                .....
                excelRow.CalculateHash();
                resp.excelRows.Add(excelRow);
             }
            return resp;
       }

This is where i am getting the error: excelRow.lstCells.Add(item.ElementAt(0));

Masriyah
  • 2,445
  • 11
  • 49
  • 91
  • 1
    you never instantiate the `List` – Marc Aug 27 '13 at 01:47
  • 1
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Aug 27 '13 at 02:03

2 Answers2

2

You need to initialize your lstCells in your ExcelRow constructor:

public class ExcelRow {
  public List<String> lstCells;
  public byte[] rowHash;
  public ExcelRow(){
     lstCells = new List<string>();
  }
  //....
}

public class ExcelInfo {
  public List<ExcelRow> excelRows = new List<ExcelRow>();
}
King King
  • 61,710
  • 16
  • 105
  • 130
1

You are not showing your ExcelRow constructor, but from the error, I am guessing you never instantiate lstCells and it remains null.

You could find this out by debugging your program and mousing over each item in the line or methodically removing one item at a time from the line until it starts working again. and deducing the problem.

lc.
  • 113,939
  • 20
  • 158
  • 187