How to add string to datatable?

I have a datatable say dt1 (which continues to modify it inside the loop). I have another datatable say dt2 (originally its null). Now I need to add dt1 lines to dt2. I tried using Merge (), but the previous dt2 lines disappear. Any idea how to do this?

+3
source share
6 answers

You clear the table dt2every time the loop starts. Try the following:

DataTable dt1 = null; DataTable dt2 = null;

for (int i = 0; i < dt3.Rows.Count; i++) 
{

    // here  "strSQL" is build which changes on the "i" value                  

    dt1 = GetDataTable(strSQL); // this returns a table with single Row

    if(dt2 == null) 
    {
       dt2 = dt1.Clone();
    }

    dt2.Merge(dt1,true);
}

Alternatively, if a query-based restriction is iapplied to the primary key column, you can use

dt2.ImportRow(dt1.Rows[0]);

instead

dt2.Merge(dt1,true);
+1
source

, dt2 = dt1.Clone(); dt2, dt1 dt2.

dt1 dt2.

+1

Use a method ImportRow, for example:

var table2 = new DataTable();

foreach(DataRow row in table1.Rows)
    table2.ImportRow(row);
+1
source

Another derivative for Joao Angelo's answer would be to initialize dt2 ahead of time, and then you can remove the null check

DataTable dt1 = null; DataTable dt2 = new DataTable();

for (int i = 0; i < dt3.Rows.Count; i++) 
{

    // here  "strSQL" is build which changes on the "i" value                  

    dt1 = GetDataTable(strSQL); // this returns a table with single Row

    dt2.Merge(dt1,true);
}
+1
source

How about this:

  DataRow[] rows = new DataRow[dt1.Rows.Count];
  dt1.Rows.CopyTo(rows, 0);
  foreach (DataRow row in rows)
  {
    dt2.Rows.Add(row);
  }
0
source

I assume your tables have the same structure

 foreach (DataRow row in dt1.Rows)
     dt2.Rows.Add(row.ItemArray);
0
source

Source: https://habr.com/ru/post/1724618/


All Articles