Question : How can i add column name in list generic?

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

Answer : How can i add column name in list generic?

Something like this is actually better:

class MyExcelSheets  
{
        public List<string> MyColumnNames { get; set; }
       public MyExcelSheets()
       {
               MyColumnNames = new List<string>();
        }
}


MyExcelSheets mes = new MyExcelSheets();

foreach (DataColumn  col in dTable.Columns)
{
       myexcelSheet.MyColumnNames.Add(col.ColumnName.ToString());

}

This ensures type safety - you can add only strings into your MyColumnNames collection.

If you're having any issues, please let me know what line is it breaking at.

Arun
Random Solutions  
 
programming4us programming4us