Two how does a DataTable with identical structures merge?
Example: Using WinForm to demonstrate that the data in table 2 is fixed, table 1 data can be added dynamically, merging the data from Table 1 and table 2 to table 3 by merging buttons
1. Provision of a public DataTable structure
///<summary>//Structure empty datatable///</summary>/// <returns></returns> Private DataTable Getemptydatatable () {datatable dt = new DataTable (); dt. Columns.Add ("Id"); Dt. Columns.Add ("Name"); return DT;}
2. Table 2 data is constructed in the form Load event
Privatevoid Form1_Load (Object sender, EventArgs e) { // constructs the data for table 2 DataTable DT2 = this . Getemptydatatable (); DataRow dr = DT2. NewRow (); dr["Id"] = guid.newguid (); dr["Name"] = " table two data "; DT2. Rows.Add (DR); This.dgv2.DataSource = dt2;}
3. Dynamically add data from table 1
///<summary>///New Table 1 Data///</summary>///<param name= "Sender" ></param>///<param name= "E" ></param>Privatevoid Btnaddtable1_click (Objectsender, EventArgs e) {This.dgv3.DataSource =Null; DataTable Dtdatasouce =This.dgv1.DataSourceAsDataTable;if (Dtdatasouce = =Null) {dtdatasouce = this. Getemptydatatable (); } DataRow dr = Dtdatasouce.newrow (); dr["Id"] = guid.newguid (); dr["Name"] = " First " + dtDataSouce.Rows.Count.ToString () + " bar data "; DTDATASOUCE.ROWS.ADD (DR); This.dgv1.DataSource = dtdatasouce;}
4. Start merging
///<summary>///Merging of 22 DataTable///</summary>///<param name= "Sender" ></param>///<param name= "E" ></param>Privatevoid Btnstartmerge_click (Objectsender, EventArgs e) {//Get table 1 data for DataTable DT1 =This.dgv1.DataSourceAsDataTable;//Get table two data for DataTable DT2 =This.dgv2.DataSourceAsDataTable;// start merging (thinking: Construct the empty table DT structure and table 1, table 2 the same will add data from table 1 table 2 to DT) //1. Arbitrarily select a table to replicate the DataTable dt = DT1. Clone (); //2. Follow the bad traversal table 1 foreach ( DataRow Dr in DT1. Rows) {dt. Rows.Add (Dr. ItemArray); } //3. Loop through Table 2 foreach ( DataRow Dr in DT2. Rows) {dt. Rows.Add (Dr. ItemArray); } // at this time DT is the combined data of table 1 and table 2 DT;
5. Demo
Merge two identically structured DataTable