DataTable Copy?

  • Thread starter Thread starter Matthew Wieder
  • Start date Start date
M

Matthew Wieder

I have a datatable as a source and I need to produce a datatable which
is all the rows in the original datatable except the first row, copied n
times. So, if I had a datatable of:

A B C
1 21 12 32
2 1 43 12
3 32 12 35

I need to output:

A B C
1 1 43 12
2 32 12 35
3 1 43 12
4 32 12 35
5 1 43 12
6 32 12 35

can anyone supply sample code?
thanks!
 
Hi Matthew,

Thank you for posting in the community!

Based on my understanding, you want to do some row based custom copy in
datatable. You want some sample code.

================================
I think you can use DataTable.ImportRow method to import a row into the new
datatable.

Do like this:
DataTable dt;
private void constructdatatable()
{
dt=new DataTable();

dt.Columns.Add("column1");
dt.Columns.Add("column2");
dt.Columns.Add("column3");

DataRow dr=dt.NewRow();
dr["column1"]=21;
dr["column2"]=12;
dr["column3"]=32;
dt.Rows.Add(dr);

dr=dt.NewRow();
dr["column1"]=1;
dr["column2"]=43;
dr["column3"]=12;
dt.Rows.Add(dr);

dr=dt.NewRow();
dr["column1"]=32;
dr["column2"]=12;
dr["column3"]=35;
dt.Rows.Add(dr);
}

private void button_Click(object sender, System.EventArgs e)
{
DataTable dtnew;
dtnew=dt.Clone();
for(int i=0;i<3;i++)
{
dtnew.ImportRow(dt.Rows[1]);
dtnew.ImportRow(dt.Rows[2]);
}

dataGrid1.DataSource=dtnew;
}

=======================================
Please apply my suggestion above and let me know if it helps resolve your
problem.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
It did help. I also need to copy a series of columns (and their data) n
times, and that seems to be more difficult. Given:
A B C
1 21 12 32
2 1 43 12
3 32 12 35

I need to produce:
A B C D E F G
1 21 12 32 12 32 12 32
2 1 43 12 43 12 43 12
3 32 12 35 12 35 12 35
 
Hi Matthew,

Thanks very much for your feedback.

I am glad it works.

For your further concern, I viewed that you have figured it out to use
DataTable.Columns.AddRange method. Please follow up there.

Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top