两个Datatable合并

两个结构一样的DataTable合并

 

1.DataTable DataTable1 = new DataTable();   
2.DataTable DataTable2 = new DataTable();   
3.DataTable newDataTable = DataTable1.Clone();   
4.  
5.object[] obj = newobject[newDataTable.Columns.Count];   
6.for (int i = 0; i < DataTable1.Rows.Count; i++)   
7.{   
8.    DataTable1.Rows[i].ItemArray.CopyTo(obj,0);   
9.    newDataTable.Rows.Add(obj);   
10.}   
11.for (int i = 0; i < DataTable2.Rows.Count; i++)   
12.{   
13.    DataTable2.Rows[i].ItemArray.CopyTo(obj,0);   
14.    newDataTable.Rows.Add(obj);   
15.}  
16.//或者   
17.DataTable DataTable1 = new DataTable();   
18.DataTable DataTable2 = new DataTable();   
19.  
20.object[] obj = newobject[DataTable1 .Columns.Count];   
21.for (int i = 0; i < DataTable2.Rows.Count; i++)   
22.{   
23.    DataTable2.Rows[i].ItemArray.CopyTo(obj,0);   
24.    DataTable1.Rows.Add(obj);   
25.}  

  

 

两个结构不同的DataTable合并

1./// <summary>    
2./// 将两个列不同的DataTable合并成一个新的DataTable    
3./// </summary>    
4./// <param name="dt1">Table表1</param>    
5./// <param name="dt2">Table表2</param>    
6./// <param name="DTName">合并后新的表名</param>    
7./// <returns></returns>   
8.  
9.private DataTable UniteDataTable( DataTable dt1 ,DataTable dt2 ,string DTName)   
10.{    
11. DataTable dt3 = dt1.Clone();   
12.for( int i = 0 ;i < dt2.Columns.Count ;i ++ )   
13. {   
14.  dt3.Columns.Add( dt2.Columns[i].ColumnName ) ;   
15. }   
16.object[] obj = newobject[dt3.Columns.Count];   
17.    
18.for (int i = 0; i < dt1.Rows.Count; i++)   
19. {   
20.  dt1.Rows[i].ItemArray.CopyTo(obj,0);   
21.  dt3.Rows.Add(obj);   
22. }   
23.       
24.if( dt1.Rows.Count >= dt2.Rows.Count )   
25. {   
26.  for( int i = 0 ;i < dt2.Rows.Count ;i++ )   
27.  {   
28.   for( int j = 0 ;j < dt2.Columns.Count ;j ++ )   
29.   {   
30.    dt3.Rows[i][j+dt1.Columns.Count] = dt2.Rows[i][j].ToString() ;   
31.   }   
32.  }   
33. }   
34.else   
35. {   
36.  DataRow dr3 ;   
37.  for( int i = 0 ;i < dt2.Rows.Count - dt1.Rows.Count ;i ++ )   
38.  {   
39.   dr3 = dt3.NewRow() ;   
40.   dt3.Rows.Add( dr3 ) ;   
41.  }   
42.  for( int i = 0 ;i < dt2.Rows.Count ;i++ )   
43.  {   
44.   for( int j = 0 ;j < dt2.Columns.Count ;j ++ )   
45.   {   
46.    dt3.Rows[i][j+dt1.Columns.Count] = dt2.Rows[i][j].ToString() ;   
47.   }   
48.  }   
49. }   
50. dt3.TableName = DTName ;   
51.return dt3 ;   
52.} 

 

posted @ 2012-11-26 16:23  落冰  阅读(566)  评论(0编辑  收藏  举报