Adding rows to a DataSet (C#)

57 views Asked by At

I have a DataSet in C# composed from three tables, with columns only, and I am trying to populate these tables by adding rows. This is my first table (destinationTable) The two columns that I am trying to add rows to are primary keys and cannot be null. However, when I try to add to them, I get this console error either on the first column or second:

ERRORE: Column 'CONFIG_NAME' does not allow nulls.

This is my code:

var newRow = destinationTable.NewRow();
newRow["APP_CODE"] = mAppCode;
destinationTable.Rows.Add(newRow);

var newRow2 = destinationTable.NewRow();
newRow2["CONFIG_NAME"] = "pippo";
destinationTable.Rows.Add(newRow2);

Same thing happens if I try to add to any other existing column. Same error. Any suggestions? Thanks.

I tried different suggestions from my coworkers but it seems impossible to populate. I tried creating a temporary empty DataSet and add those columns there instead, and then copy everything to this DataSet, but I get the same error.

EDIT:

The problem revolved on another issue related on the DataSet population. However, the answer provided by the users here are correct in context; only one row is needed.

1

There are 1 answers

0
harti20 On BEST ANSWER

As @SoftwareDeveloper mentioned in his comment, you should initialize all column values once and then add the row to the desired table. The error you're facing in your comment is caused because you try to add the new row to a different DataTable:

var newRow = destinationTable.NewRow(); // <- newRow is created from destinationTable
newRow["APP_CODE"] = mAppCode;
newRow["CONFIG_NAME"] = "pippo";
sourceTable.Rows.Add(newRow); // <- you have to use the same DataTable here

When using Rows.Add() You have to add the new row to the same DataTable you used for the NewRow().