views:

52

answers:

2
 class MyExcelSheets
    {
        public List MyColumnNames { get; set; }
    }

how can i add Excel data's column name in "List MyColumnNames ". it returns to me Object reference not set to an instance of an object.

i want to use above class in:

     myexcelSheet = new MyExcelSheets();
                myexcelSheet.MyColumnNames = new MyExcelSheets().MyColumnNames;
                foreach (DataColumn col in dTable.Columns)
                  myexcelSheet.MyColumnNames.Add(col.ColumnName.ToString());

How can i solve it?

Error: NullReferenceException

+2  A: 

Assuming that public List MyColumnNames { get; set; } is actually declared as public List<string> MyColumnNames { get; set; }

The row:

myexcelSheet.MyColumnNames = new MyExcelSheets().MyColumnNames;

Should be:

 myexcelSheet.MyColumnNames = new List<string>;

Though it would normally be better to do this in a constructor or something.

ho1
+2  A: 

The Code myexcelSheet.MyColumnNames = new MyExcelSheets().MyColumnNames; only obtains the reference to the property , but it doesnt instantiate that.

Adding the code

this. MyColumnNames = new List<string>;

in a static constructor will solve the issue , as this part of the code will be called by the run time and we dont have to worry about instantiating state transfer objects (as it is in this case)

E.g.,

static MyExcelSheets(){this. MyColumnNames = new List<string>; }

Thanks, Vijay

vijaysylvester