Tom Blouise
Tom Blouise

Reputation: 13

Merge DataTables in C#

I have two DataTables in an ASP.NET application written in C# (dtA and dtB). The both get filled from textboxes from user input. Each of them will only have one datarow at a time. For example, dtA can have the following values [ABC, DEF] where the column names are first name and last name, and dtB can having the following values [50, 100, 95] where the column names are grades. I need to know how to combine the two of these tables into a new datatable called dtC this way I can return dtC.

Upvotes: 1

Views: 691

Answers (1)

Amir
Amir

Reputation: 9637

Something like:

        var dtC = new DataTable("CombinationOfBoth");
        dtC.Columns.Add("Firstname",typeof(string));
        dtC.Columns.Add("Lastname", typeof (string));
        dtC.Columns.Add("Grade1", typeof (int));
        dtC.Columns.Add("Grade2", typeof(int));
        dtC.Columns.Add("Grade3", typeof(int));

        dtC.Merge(dtA,false,MissingSchemaAction.Ignore);
        dtC.Merge(dtB, false, MissingSchemaAction.Ignore);

Please note that the dtA should have same column names as "Firstname", and "LastName", also dtB should have "Grade1","Grade2","Grade3"

or you can change the name of the columns on the dtC to be exactly same as the ones that are on dtA and dtB

Upvotes: 2

Related Questions