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.
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With