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

c#, datatable

Solution

You should make sure that you actually initialize the dtMain:

DataTable dtMain; //datatable not initialized, it will be null

DataTable dtMain = new DataTable(); //initialized datatable

Problem

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?

Original source