none
Merging two columns from two data tables. RRS feed

  • Question

  • hi,

    I have two data tables

    1.DataTable1 containing columns One,Two and Three

    2.DataTable2 containing columns One,Two and Four

     

    I would like to Merge the  2nd Table with the first table with the values. in the format of

    One | Two| Three | Four

    When i try to merge those tables with DataSet.Merge() and DataTable.Merge() method, the columns only gets added and not the values in it.

     

    Could any one tell me the solution to perform the same with a code snippet

     

    Thanks in advance.

     

     

     

    Monday, February 18, 2008 7:55 AM

All replies

  •  

    Try this,

     

    Code Snippet

    //   use

    //  public void Merge (
    //  DataTable table,
    //  bool preserveChanges,
    //  MissingSchemaAction missingSchemaAction)

     

    DataTable1.Merge(DataTable2,True,MissingSchemaAction.Add)

     

     

     

    Example:

     

    Code Snippet

     

    DataTable dt1,dt2;

    DataColumn dc;

    DataRow dr;

     

    //Create table 1

    dt1 =new DataTable();

    dc=new DataColumn("id",typeof(int));

    dt1.Columns.Add(dc);

     

    dr=dt1.NewRow();

    dr[0]=1;

    dt1.Rows.Add(dr);

     

    dr=dt1.NewRow();

    dr[0]=2;

    dt1.Rows.Add(dr);

     

    //Create table 1

    dt2=new DataTable();

    dc=new DataColumn("No.",typeof(int));

    dt2.Columns.Add(dc);

     

    dr=dt2.NewRow();

    dr[0]=10;

    dt2.Rows.Add(dr);

     

    dr=dt2.NewRow();

    dr[0]=20;

    dt2.Rows.Add(dr);

     

    //Merge.

    dt1.Merge(dt2,true,MissingSchemaAction.Add );

     

     

     

    Output:

    id    No.

    1      -

    2      -

    -     10

    -     20

     

    Hope this helps.

    Monday, February 18, 2008 6:54 PM