The code is as follows:
Copy Code code as follows:
<summary>
Merging two columns of different DataTable into a new DataTable
</summary>
<param name= "DT1" > Source table </param>
<param name= "DT2" > Tables to be merged </param>
<param name= "PrimaryKey" > Need to row the list (not to row the weight) </param>
<param name= "MaxRows" > The maximum number of rows after the merged table </param>
<returns> after the merger of the Datatable</returns>
public static DataTable Mergedatatable (DataTable Dt1, DataTable DT2, String primaryKey, int maxRows)
{
Determine if you need to merge
if (DT1 = = NULL && DT2 = null)
{
return null;
}
if (DT1 = = null && DT2!= null)
{
Return DT2. Copy ();
}
else if (dt1!= null && DT2 = null)
{
Return DT1. Copy ();
}
Copy the DT1 data
DataTable dt = dt1. Copy ();
Supplemental DT2 structure (columns not in DT1) to DT
for (int i = 0; i < DT2. Columns.count; i++)
{
String cName = Dt2. Columns[i]. ColumnName;
if (!dt. Columns.contains (CName))
{
Dt. Columns.Add (New DataColumn (CName));
}
}
Copy the DT2 data
if (DT2. Rows.Count > 0)
{
Type t = dt2. Rows[0][primarykey]. GetType ();
BOOL Isneedfilter = string. IsNullOrEmpty (PrimaryKey)? False:true;
BOOL Isneedquotes = T.name = = "String"? True:false;
int mergetablenum = dt. Rows.Count;
for (int i = 0; i < DT2. Rows.Count && Mergetablenum < maxRows; i++)
{
bool Isneedadd = true;
If you need to row weight, decide if you want to add the forward
if (Isneedfilter)
{
String primaryvalue = Dt2. Rows[i][primarykey]. ToString ();
String fileter = PrimaryKey + "=" + Primaryvalue;
if (isneedquotes)
{
Fileter = PrimaryKey + "= '" + primaryvalue + "'";
}
datarow[] DRS = dt. Select (Fileter);
if (DRS!= null && Drs. Length > 0)
{
Isneedadd = false;
}
}
Add data
if (Isneedadd)
{
DataRow dr = dt. NewRow ();
for (int j = 0; j < dt.) Columns.count; J + +)
{
String cName = dt. COLUMNS[J]. ColumnName;
if (DT2. Columns.contains (CName))
{
Prevent errors due to different types of assignment in the same field
if (DT2. Rows[i][cname]!= null && DT2. Rows[i][cname]!= dbnull.value && DT2. Rows[i][cname]. ToString ()!= "")
{
Dr[cname] = DT2. Rows[i][cname];
}
}
}
Dt. Rows.Add (DR);
mergetablenum++;
}
}
}
return DT;
}