C# 表复制和数据行的复制说明(Clone、ImportRow 、Copy )

/// <summary>        

/// 构建测试数据表        

/// </summary>        

/// <returns></returns>        

private DataTable GetTB()        

{            

//定义表结构            

DataTable dt = new DataTable();            

dt.Columns.Add("FactoryId");            

dt.Columns.Add("FactoryName");            

dt.Columns.Add("FactoryDescribe");            

dt.Columns.Add("FactoryCode");            

dt.Columns.Add("IsActivation");

dt.TableName = "TbFactor";            

//填充数据            

dt.Rows.Add("1", "河北钢铁", "集团总公司", "1000", 1);            

dt.Rows.Add("2", "唐山钢铁", "集团子公司", "1001", 0);            

dt.Rows.Add("3", "宣化钢铁", "集团子公司", "1002", 0);            

dt.Rows.Add("4", "宝钢", "宝山钢铁集团", "2000", 1);            

return dt;        

}        

 

/// <summary>        

/// 表的复制(结构和数据)及行的复制示例        

/// </summary>        

private void TableDemo()        

{            

DataTable dt = GetTB();            

DataTable dt2 = dt.Clone();//克隆表结构            

DataTable dt3 = dt.Copy();//复制表结构和数据            

if (dt.Rows.Count > 0)            

{                

// 示例1:复制指定的行到新表                

foreach (DataRow dr in dt.Rows)                

{                    

if (dr["FactoryId"].ToString() == "1" && dr["IsActivation"].ToString() != "1")                    

{                        

dt2.ImportRow(dr);//复制行数据到新表                    

}                

}                

//示例2: Copy from the results of a Select method

/ /select返回的是一个行数组DataRow[]                

foreach (DataRow dr in dt.Select("FactoryId='1'"))                

{                    

dt2.ImportRow(dr);//复制行数据到新表                

}                

//示例3:Copy from the results of a DataView.                

DataView dv = dt.DefaultView;                

dv.RowFilter = "FactoryCode = '1002'";                

foreach (DataRowView rv in dv)                

{                    

dt2.ImportRow(rv.Row););//复制行数据到新表                

}                           

}        

}

posted on 2014-12-01 14:11  秋天  阅读(11421)  评论(0编辑  收藏  举报

导航