protected void Page_Load(object sender, EventArgs e)
{
creatDataTable();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable DataTableA = ViewState["datatable1"] as DataTable;
DataTable DataTableB = ViewState["datatable2"] as DataTable;
DataTableB.Columns.Add("flag", typeof(String));
DataTableB.Columns["flag"].DefaultValue = "×";
DataView dv1 = DataTableA.DefaultView;
DataView dv2 = DataTableB.DefaultView;
foreach (DataRowView drv1 in dv1)
{
dv2.RowFilter = " id = '" + drv1["id"].ToString() + "'";
if (dv2.Count > 0)
{
if (CompareUpdate(drv1, dv2[0]))//比较是否相同
{
dv2[0].Row["flag"] = "√";
}
else
{
dv2[0].Row["flag"] = "×";
}
}
}
GridView3.DataSource = MergeDataTable(DataTableA,DataTableB);
GridView3.DataBind();
}
#region 创建测试DataTable
protected void creatDataTable()
{
//第一步 先初始化数据
DataTable dtA = new DataTable();
dtA.Columns.Add("id", typeof(int));
dtA.Columns.Add("name", typeof(string));
dtA.Rows.Add(1, "a");
dtA.Rows.Add(2, "b");
dtA.Rows.Add(3, "c");
dtA.Rows.Add(4, "d");
DataTable dtB = dtA.Clone();
dtB.Rows.Add(1, "a");
dtB.Rows.Add(2, "d");
dtB.Rows.Add(3, "e");
dtB.Rows.Add(4, "f");
GridView1.DataSource = dtA;
GridView1.DataBind();
GridView2.DataSource = dtB;
GridView2.DataBind();
ViewState["datatable1"] = dtA;
ViewState["datatable2"] = dtB;
}
#endregion
#region 比较数据行是否相同
/// <summary>
/// 比较数据行是否相同
/// </summary>
/// <param name="dr1"></param>
/// <param name="dr2"></param>
/// <returns></returns>
private static bool CompareUpdate(DataRowView dr1, DataRowView dr2)
{
//行里只要有一项不一样,整个行就不一样,无需比较其它
object val1;
object val2;
for (int i = 1; i < dr1.Row.ItemArray.Length; i++)
{
val1 = dr1[i];
val2 = dr2[i];
if (!val1.Equals(val2))
{
return false;
}
}
return true;
}
#endregion
#region 合并两个DataTable列
/// <summary>
/// 合并两个DataTable列
/// </summary>
/// <param name="dt1"></param>
/// <param name="dt2"></param>
/// <returns></returns>
public static DataTable MergeDataTable(DataTable dt1, DataTable dt2)
{
//定义dt的行数
int dtRowCount = 0;
//dt的行数为dt1或dt2中行数最大的行数
if (dt1.Rows.Count > dt2.Rows.Count)
{
dtRowCount = dt1.Rows.Count;
}
else
{
dtRowCount = dt2.Rows.Count;
}
DataTable dt = new DataTable();
//向dt中添加dt1的列名
for (int i = 0; i < dt1.Columns.Count; i++)
{
dt.Columns.Add(dt1.Columns[i].ColumnName + "1");
}
//向dt中添加dt2的列名
for (int i = 0; i < dt2.Columns.Count; i++)
{
dt.Columns.Add(dt2.Columns[i].ColumnName + "2");
}
for (int i = 0; i < dtRowCount; i++)
{
DataRow row = dt.NewRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
for (int k = 0; k < dt1.Columns.Count; k++) { if ((dt1.Rows.Count - 1) >= i) { row[k] = dt1.Rows[i].ItemArray[k]; } }
for (int k = 0; k < dt2.Columns.Count; k++) { if ((dt2.Rows.Count - 1) >= i) { row[dt1.Columns.Count + k] = dt2.Rows[i].ItemArray[k]; } }
}
dt.Rows.Add(row);
}
return dt;
}
#endregion
比较两个DataTable中不同的记录,且合并两个DataTable的列显示,有图
本文转载:CSDN博客