更改不同值的单元格颜色 – Gridview

我需要区分两个连续的细胞。

连续的每一个,如果它们具有不同的值,则在数据绑定时将值指向gridview。

因此,如果在行1中我有单元格“ABC”而在行2中我有单元格“CBA”。

我需要用不同的颜色为每个单元格着色。

最好的方法是什么?

你可以在gridview的rowdatabound事件上做到这一点。 将上一行保留在viewstate或session中,并将其与下一行匹配。 如果不匹配,请更改颜色,否则不要更改。

这称为条件格式

您可以在标记中启用RowDataBound事件

  

并将其放在Code-Behind文件中。

 protected void RowDataBound(Object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.DataRow) { if(e.Row.RowIndex == 0) // This is row no.1 if(e.Row.Cells[0].Text == "ABC") e.Row.Cells[0].BackColor = Color.Red; if(e.Row.RowIndex == 1) // This is row no.2 if(e.Row.Cells[0].Text == "CBA") e.Row.Cells[0].BackColor = Color.Green; } } 

在页面的html部分添加到gridview OnRowDataBound =“gridView1_DataBinding”。 然后添加事件处理程序codebehind:

 protected void gridView1_DataBinding(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.DataRow) return; var c = e.Row.FindControl("IdOfControl") as Label; if(c != null) { if (c.Text == "ABC") e.Row.BackColor = GetColor("Gray"); if (c.Text == "BCA") e.Row.BackColor = GetColor("Green"); } } private Color GetColor(string color) { return Color.FromName(color); } 

最好的问候,迪马。

如果我理解你正确,你想要改变一个单元格的颜色,取决于它的价值。 如果这是正确的,你可以尝试这样:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if ((Label)e.Row.Cells[0].FindControl("ValueHoldingControl").Text == "ABC") { //Coloring the cell } } } 
 void gvShowFullDetail_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#AECD6F"); } }