how do you create a datatable clone but with a different row count

  • Thread starter Thread starter hs
  • Start date Start date
H

hs

Hi
I have a DataTable object which contains say 1000 records. I want to clone
this DataTable but the clone must only contain the rows i want e.g. rows
0-240 (i.e. a subset)

thanks
hs
 
the immediate way that comes to mind is to create a method, maybe it takes
in a start and end index that you want to "clone" as you put it.

Then this method creates a new blank table with the same columns, and parses
through the original table, creating a row and adding it to the destination.

there may be other simpler ways of doing it.

lemme know if you want help with the implementation.

Dan.
 
Thanks Daniel,
There maybe one thing you can help me with. i'm doing the following (dt is
the original DataTable object), but the Rows Collection is not being
populated. Any Ideas?

DataTable datatable = new DataTable();

for(int i=0; i<dt.Columns.Count; i++)
{
DataColumn current_col = dt.Columns;
DataColumn new_col = new DataColumn(current_col.ColumnName,
Type.GetType(current_col.DataType.FullName));
datatable.Columns.Add(new_col);
}
// loop thru datatable.rows collection
for(int i=iStart; i<dt.Rows.Count; i++)
{
DataRow row = dt.NewRow();
row.ItemArray = dt.Rows.ItemArray;
dt.Rows.Add(row);
}
dt.AcceptChanges();
 
Hi hs,

Maybe you have made a mistake on the output datatable. In your code, you
used dt.Rows.Add(row) which adds the new generated row to your original
datatable. Try to replace it with "datatable".

DataTable datatable = new DataTable();

for(int i=0; i<dt.Columns.Count; i++)
{
DataColumn current_col = dt.Columns;
DataColumn new_col = new
DataColumn(current_col.ColumnName,

Type.GetType(current_col.DataType.FullName));
datatable.Columns.Add(new_col);
}
// loop thru datatable.rows collection
for(int i=0; i<24; i++)
{
DataRow row = datatable.NewRow();
row.ItemArray = dt.Rows.ItemArray;
datatable.Rows.Add(row);
}
datatable.AcceptChanges();
 
Thanks Kevin
You were absolutely correct! I did a copy/paste but didn't bother to change
the code. Oh well. These things happen i suppose. Thanks for your help.
 
Back
Top