How to Insert New Row Into Existing DataTable While Looping DataTable

  • Thread starter Thread starter Kelvin
  • Start date Start date
Kelvin said:
Dear All,

Please help.
Same as subject !!!

Inserting a new row is the same whether you are looping or not.

DataTable dt = new DataTable();
DataRow row = dt.NewRow();
row["columnname"] = "whatever";
dt.Rows.Add(row);
dt.AcceptChanges();

If you are looking for something more specific to your situation, then
you need to post some code.

Lowell
 
Hi,

No really, if you are iterating a collection you cannot change it, or you
may get an exception.

IIRC I had a similar problem but with removing instead of adding, solution:
Use an ArrayList to keep the rows that you will add
after the loop add all the rows from the ArrayList into the datatable.


Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation



Lowell Heddings said:
Kelvin said:
Dear All,

Please help.
Same as subject !!!

Inserting a new row is the same whether you are looping or not.

DataTable dt = new DataTable();
DataRow row = dt.NewRow();
row["columnname"] = "whatever";
dt.Rows.Add(row);
dt.AcceptChanges();

If you are looking for something more specific to your situation, then you
need to post some code.

Lowell
 
Hi,

Use an ArrayList while you are looping and later add them to the table

Cheers,
 
Ignacio,

Wouldn't it be easier to do this?

// Get the number of rows.
// dt is the data table.
int rows = dt.Rows.Count;

// The data row.
DataRow row;

// Cycle
for (int index = 0; index < rows; ++index)
{
// Get the row.
row = dt.Rows[index];

// Add row if necessary.
}

This way, you avoid an extra loop, and you prevent processing of the
added rows.

Hope this helps.
 
Back
Top