[c#] Merge 2 DataTables and store in a new one

If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do:

 dtOne.Merge(dtTwo);

Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?

I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:

//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);

This question is related to c# datatable

The answer is


dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.


DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
    dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
    dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.


Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.


This is what i did for merging two datatables and bind the final result to the gridview

        DataTable dtTemp=new DataTable();
        for (int k = 0; k < GridView2.Rows.Count; k++)
        {
            string roomno = GridView2.Rows[k].Cells[1].Text;
            DataTable dtx = GetRoomDetails(chk, roomno, out msg);
            if (dtx.Rows.Count > 0)
            {
                dtTemp.Merge(dtx);
                dtTemp.AcceptChanges();

            }
        }