Reputation: 291
I have some code to compare two DataTables. If one table has more rows than the other, I want to be able to add blank rows until they have an equal row count.
I have tried this:
for (int i = 0; i < difference; i++)
{
table.Rows.Add();
}
as well as
DataRow newRow = table.NewRow();
table.ImportRow(newRow);
and
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
None of these seem to work.
table.Rows.Add() (with and without the param) seems to break me out of the loop after one iteration
ImportRow loops around the appropriate amount of times, but only adds one new row
Where am I going wrong?
Upvotes: 0
Views: 1987
Reputation: 7713
The following code works ok to me:
DataTable dtable = new DataTable();
dtable.Columns.Add("Column1");
dtable.Columns.Add("Column2");
for (int i = 0; i < 10; i++)
{
DataRow newRow = dtable.NewRow();
dtable.Rows.Add(newRow);
}
It,as expected, adds 10 empty rows to my DataTable. If this doesn't work to you, maybe your DataTable has a primary key or other restriction that prevents to add those empty rows. Show us your DataTable definition in that case.
Edit
In this example based on the previous I define a primary key, so this code doesn't work:
DataTable dtable = new DataTable();
dtable.Columns.Add("Key");
dtable.Columns.Add("Column2");
dtable.PrimaryKey = new DataColumn[]{dtable.Columns[0]};
for (int i = 0; i < 10; i++)
{
DataRow newRow = dtable.NewRow();
dtable.Rows.Add(newRow);
}
It fails with a NoNullAllowedException
, this is, the Primary Key can't be null.
The following code works:
for (int i = 0; i < 10; i++)
{
DataRow newRow = dtable.NewRow();
newRow["Key"] = i;
dtable.Rows.Add(newRow);
}
Because I'm setting a value to the Primary Key. In your case, it depends of the DataType of your PrimaryKey, and you must check also if the values you are "inventing" are already present or it will also fail.
I hope this is clear now for you.
Upvotes: 1
Reputation: 3009
With this test:
var table = new DataTable();
for (int i = 0; i < 5; i++)
{
var row = table.NewRow();
table.Rows.Add(row);
}
The DataTable table contains 5 rows.
Upvotes: 0