两个不同的 DataTable 合并列及数据

DataTable dt_0 = _ep.ds_Pocedure("SP_USP_Select_CGXBJ_BJD_By_Id", "'" + ViewState["XMID"].ToString() + "','" + jhid + "','" + tjdw + "','" + txt_CLMC.Value.Trim() + "'").Tables[0];
DataTable dt_1 = _ep.ds_Pocedure("SP_USP_Select_CGXBJ_BJD_By_Id", "'" + ViewState["XMID"].ToString() + "','" + jhid + "','" + tjdw + "','" + txt_CLMC.Value.Trim() + "'").Tables[1];
DataTable dt = UniteDataTable(dt_0, dt_1, "dt");
private DataTable UniteDataTable(DataTable DataTable1, DataTable DataTable2, string DTName)
        {
            DataTable newDataTable = DataTable1.Clone();
            for (int i = 0; i < DataTable2.Columns.Count; i++)
            {
                newDataTable.Columns.Add(DataTable2.Columns[i].ColumnName);
            }
            object[] obj = new object[newDataTable.Columns.Count];
            for (int i = 0; i < DataTable1.Rows.Count; i++)
            {
                DataTable1.Rows[i].ItemArray.CopyTo(obj, 0);
                newDataTable.Rows.Add(obj);
            }
            if (DataTable1.Rows.Count >= DataTable2.Rows.Count)
            {
                for (int i = 0; i < DataTable2.Rows.Count; i++)
                {
                    for (int j = 0; j < DataTable2.Columns.Count; j++)
                    {
                        newDataTable.Rows[i][j + DataTable1.Columns.Count] = DataTable2.Rows[i][j].ToString();
                    }
                }
            }
            else
            {
                DataRow dr3;
                for (int i = 0; i < DataTable2.Rows.Count - DataTable1.Rows.Count; i++)
                {
                    dr3 = newDataTable.NewRow();
                    newDataTable.Rows.Add(dr3);
                }
                for (int i = 0; i < DataTable2.Rows.Count; i++)
                {
                    for (int j = 0; j < DataTable2.Columns.Count; j++)
                    {
                        newDataTable.Rows[i][j + DataTable1.Columns.Count] = DataTable2.Rows[i][j].ToString();
                    }
                }
            }
            newDataTable.TableName = DTName;
            return newDataTable;
        }

 

posted @ 2022-09-28 17:31  尧荣华  阅读(26)  评论(0编辑  收藏  举报