C Sharper
C Sharper

Reputation: 8626

Copy one datatable into another

I have 1st datatable as:

dtOld

Columns:

C E

second datatable as:

dtNew:

A B C D E F

I just wanted to copy stOld data into dtNew with specified columns.

i.e.:

C col's value of dtOld should copy in D col value of dtNew..and E Col to F col

I tried some complex logic, but it does not worked.

Is there any way to solve this.

I tried as:

DataTable dtOld = new DataTable();
                        dtOld = ds.Tables[0];
                        string[] columns = { "c", "E" };
                        string[] columns2 = { "D", "F " };
                        foreach (DataRow sourcerow in dtOld.Rows)
                        {
                            DataRow destRow = dtNew.NewRow();
                            int cntm = 0;
                            foreach (string colname in columns)
                            {
                                destRow[columns2[cntm]] = sourcerow[colname];
                                cntm++; 
                            }
                            dtNew.Rows.Add(destRow);
                        }

Please help me.

Upvotes: 0

Views: 628

Answers (2)

nima
nima

Reputation: 6733

    foreach (DataRow row in dtOld.Rows)
        dtNew.LoadDataRow(new[]
                                  {
                                      null, // default value
                                      null,
                                      null,
                                      row["C"],
                                      null,
                                      row["E"]
                                  }, LoadOption.Upsert);

Upvotes: 0

Steve
Steve

Reputation: 216293

It is just a simple copy from a fixed set of columns to another set, so why to complicate things?

foreach (DataRow sourcerow in dtOld.Rows)
{
    DataRow destRow = dtNew.NewRow();
    destRow["D"] = sourcerow["c"];
    destRow["F"] = sourcerow["E"];
    dtNew.Rows.Add(destRow);
}

Upvotes: 2

Related Questions