firefalcon
firefalcon

Reputation: 510

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?

Upvotes: 4

Views: 17383

Answers (4)

Biswajeet
Biswajeet

Reputation: 362

I had a rather different issue where in the the value items were not available

Consider following:

DataTable dtStatusDetails = new DataTable();
    dtStatusDetails.Columns.Add("D1", typeof(string));
    dtStatusDetails.Columns.Add("D2", typeof(string));
dtStatusDetails.Rows.Add(
    data1.Value.ToString(),
    data2.Value.ToString(),
);

Here data1 was of null value, and the exception was displaying the same error at line 3 (in this case) line before adding rows. Putting a null('?') check helped me.

This should be help full if some one forgets a null check

Upvotes: 0

Alex Filipovici
Alex Filipovici

Reputation: 32561

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

Upvotes: 6

TheTechGuy
TheTechGuy

Reputation: 17354

The other case where one can get null reference during merge is the column names are different, even by case

You might get null reference exception when the two table have primary keys that differ in only case. source

This was exactly my problem. The column names of primary keys in both datatables must be same!

Upvotes: 1

Derek
Derek

Reputation: 8628

You need to Initialize your DataTable like this:-

DataTable dtMain = new DataTable();

If you have created it like this:-

DataTable dtMain;

Then its null object.

Upvotes: 0

Related Questions