Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add the same DataRow to a DataTable multiple times?

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.

like image 803
Eric Anastas Avatar asked Aug 26 '09 04:08

Eric Anastas


2 Answers

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);
like image 172
apiguy Avatar answered Oct 01 '22 07:10

apiguy


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.

like image 22
user1544428 Avatar answered Oct 01 '22 05:10

user1544428