两个结构一模一样的DataTable如何合并?
例子:使用Winform进行演示,表2的数据为固定的,表1的数据可以动态添加,通过合并按钮合并表1和表2的数据到表3
1.规定公共的DataTable结构
/// <summary> /// 构造空的DataTable /// </summary> /// <returns></returns> private DataTable GetEmptyDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("Id"); dt.Columns.Add("Name"); return dt; }
2.窗体加载事件中构造表2的数据
private void Form1_Load(object sender, EventArgs e) { //构造表2的数据 DataTable dt2 = this.GetEmptyDataTable(); DataRow dr = dt2.NewRow(); dr["Id"] = Guid.NewGuid(); dr["Name"] = "表二的数据"; dt2.Rows.Add(dr); this.dgv2.DataSource = dt2; }
3.动态添加表1的数据
/// <summary> /// 新增表1数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAddTable1_Click(object sender, EventArgs e) { this.dgv3.DataSource = null; DataTable dtDataSouce = this.dgv1.DataSource as DataTable; if (dtDataSouce == null) { dtDataSouce = this.GetEmptyDataTable(); } DataRow dr = dtDataSouce.NewRow(); dr["Id"] = Guid.NewGuid(); dr["Name"] = "第" + dtDataSouce.Rows.Count.ToString() + "条数据"; dtDataSouce.Rows.Add(dr); this.dgv1.DataSource = dtDataSouce; }
4.开始合并
/// <summary> /// 合并两2个DataTable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStartMerge_Click(object sender, EventArgs e) { //得到表1的数据 DataTable dt1 = this.dgv1.DataSource as DataTable; //得到表二的数据 DataTable dt2 = this.dgv2.DataSource as DataTable; //开始合并(思路:构造空的表dt结构和表1、表2相同 将表1表2的数据添加到dt中) //1. 任意选择一个表进行复制 DataTable dt = dt1.Clone(); //2.循坏遍历表1 foreach (DataRow dr in dt1.Rows) { dt.Rows.Add(dr.ItemArray); } //3.循环遍历表2 foreach (DataRow dr in dt2.Rows) { dt.Rows.Add(dr.ItemArray); } //此时dt就是表1和表2的合并数据 this.dgv3.DataSource = dt; }
5.演示