Mujtaba
Mujtaba

Reputation: 85

How I can Merge two datatable into one datatable in c#

I have tow datatables and i want to merge them and want the output like this;

Table1 values:

FirstName   LastName    
  AAA         BBB         
  AAA         BBB

Table2 values: *

FullName
  CCC
  CCC

*

now i want that FullName's value and FirstName's value merge into One column of Firstname and out should be like that after merging....

FirstName   LastName    
  AAA         BBB         
  AAA         BBB         
  CCC
  CCC   

Both out tables have the column of FirstName and LastName from dtable1 and FullName from dtable2

i have this code in my c# application

             DataSet firstGrid = new DataSet();
            DataSet secondGrid = new DataSet();
            DataTable table1 = dataGridView3.DataSource as DataTable;
            DataTable table2 = dataGridView2.DataSource as DataTable;
            DataColumn[] colunm = new DataColumn[table1.Columns.Count];



            DataTable table3 = new DataTable();
           // table3.;
            table3 = table1.Copy();

            table3.Merge(table2);
            dataGridView1.DataSource = table3;

Upvotes: 1

Views: 9793

Answers (2)

Sudhakar B
Sudhakar B

Reputation: 1563

You can try this

for(int i=0;i<dataTable2.Rows.Count;i++)
{
    DataRow drTemp=dataTable1.NewRow();
    drTemp[0]=dataTable2.Rows[i][0];
    drTemp[1]="";
    dataTable1.Rows.Add(drTemp);
}

Basically you are inserting fullnames to the table1 first name and with empty value for last name. Finally dataTable1 will be merged with dataTabe2.

Upvotes: 1

Kane
Kane

Reputation: 16802

Is this what you are looking for?

SELECT FirstName, LastName
FROM Table1

UNION

SELECT FullName AS 'FirstName', NULL AS 'LastName'
FROM Table2

Upvotes: 2

Related Questions