日期:2014-05-17 浏览次数:20456 次
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable dt2 = new DataTable(); dt2.Columns.Add("id"); dt2.Columns.Add("name"); dt2.Rows.Add("0001", "name1"); dt2.Rows.Add("0002", "name3"); dt2.Rows.Add("0004", "name4"); GridView2.DataSource = dt2; GridView2.DataBind(); DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("name"); dt.Rows.Add("0001", "name1"); dt.Rows.Add("0002", "name2"); dt.Rows.Add("0003", "name3"); GridView1.DataSource = dt; GridView1.DataBind(); // 把多出的行的背景色变成红色 if (GridView1.Rows.Count > GridView2.Rows.Count) { for (int i = GridView2.Rows.Count; i < GridView1.Rows.Count; i++) { GridView1.Rows[i].BackColor = Color.Red; } } else if (GridView1.Rows.Count < GridView2.Rows.Count) { for (int i = GridView1.Rows.Count; i < GridView2.Rows.Count; i++) { GridView2.Rows[i].BackColor = Color.Red; } } } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { // 数据绑定的时候根据现在的值去跟另一个比较,不同的背景色设置红色 // 注意:GridView2要先完成数据绑定,然后在GridView1_RowDataBound的绑定事件里去比较 // 也可以在两个都完成绑定后,通过双重循环来直接遍历gridview比较 if (e.Row.RowType != DataControlRowType.DataRow) { return; } if (e.Row.RowIndex >= GridView2.Rows.Count) { return; } for (int i = 0; i < e.Row.Cells.Count; i++) { DataRowView drv = (DataRowView)e.Row.DataItem; if (!GridView2.Rows[e.Row.RowIndex].Cells[i].Text.Equals(drv.Row[i].ToString())) { GridView2.Rows[e.Row.RowIndex].Cells[i].BackColor = Color.Red; e.Row.Cells[i].BackColor = Color.Red; } } }