Reputation: 22233
If I have a DataTable and want to create a new row I first call DataTable.NewRow()
which returns a DataRow. This row then has the schema of the Table, and I can set the value of each field in the row. At this point does the Table "know" about the Row, or does that only happen after I call DataTable.Rows.Add(DataRow row)
?
If I call DataTable.Rows.Add()
more then once are duplicate rows created in the data table with duplicate values?
The reason I ask is I'm trying to write a recursive function that will iterate down a tree structure and populate a DataTable with values. So I have situations where rows being created for each child will have columns that have all the same values because they come from the parent.
So my idea was to pass a DataRow with the parent's information to each child. The child would add its information and then add the row to the table. But I'm trying to figure out if I need to call DataTable.NewRow()
for each child, or if new rows will be created automatically if I add the same row multiple times.
Upvotes: 7
Views: 10661
Reputation: 150
Yes, old question. But Michael's answer does work. I needed to add multiple duplicate rows to a DataTable
for a scheduling app. With dt.Rows.Add(_Users)
I got the error:
This row already belongs to this table
But using this, I could loop through and hold as many positions open for a job as needed Where "Length" is the number of positions to hold open for a job:
int Length = int.Parse(TextBox6.Text.Trim());
for (int i = 0; i < Length; i++)
{
Users.Rows.Add("9999", "Open");
}
Searching Google for this sucks, because most people want to remove duplicate rows in a DataTable
, and not add duplicate rows in a DataTable
.
Upvotes: 1
Reputation: 1
i recommend that you put the data in a array and then add the data to data table e.g.
yourDataTable.Rows.Add(data[0]........);
newdatarow
will generate exception error
Upvotes: -1
Reputation: 5362
No, but it's easy to copy a row so you can get what you want (assumes the existing row is in a variable called existingRow):
var newRow = dataTable.NewRow();
newRow.ItemArray = existingRow.ItemArray;
dataTable.Rows.Add(newRow);
Upvotes: 16
Reputation: 187110
No, it will generate an exception of type System.ArgumentException.
Upvotes: 0