开发者

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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜