firefalcon firefalcon - 2 months ago 8
C# Question

Object reference not set to an instance of an object when adding DataColumn into DataTable

I am getting object reference not set to an instance of an object when I try to add new Column into Datatable. Here is my code:

DataColumn clUniqueID = new DataColumn();

clUniqueID.Caption = "UniqueID";
clUniqueID.ColumnName = "UniqueID";
clUniqueID.DataType = typeof(int);
dtMain.Columns.Add(clUniqueID);


dtMain
is a public DataTable. I put this code on form loading in my Win applicatin and when I try to load my form it is throwing Error.
Any ideas?

Answer

You should make sure that you actually initialize the dtMain:

DataTable dtMain;//not initialized, will be null

DataTable dtMain = new DataTable();//initialized