2010-12-13 70 views
9

我需要区分两个连续的单元格。在不同的值上更改单元格颜色 - Gridview

当数据绑定到gridview的值时,如果它们具有不同的值,那么它们中的每一个都是连续的。

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

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

这样做的最佳方法是什么?

回答

1

你可以在gridview的rowdatabound事件上做到这一点。将前一行保留在视图状态或会话中,并将其与下一行进行匹配。如果不匹配,则更改颜色,否则不要更改。

+0

该解决方案的工作原理是使用viewstate获取最后一行值。谢谢。 – 2010-12-13 11:31:09

13

这就是所谓的条件格式

您可以在标记

<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound"> 

</asp:GridView> 

使RowDataBound事件,并把这个在您的代码隐藏文件。

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; 
    } 
} 
+0

该解决方案通过调整代码稍微有效。我没有使用if(e.Row.RowIndex == 0)作为我的GridView总是返回1行。我还使用了for循环来遍历gridview中的所有单元格 – 2016-08-03 10:06:20

2

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

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 
     } 
    } 
} 
4

添加到你的GridView在页面OnRowDataBound =“gridView1_DataBinding”的HTML部分。然后添加事件处理程序代码隐藏:

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); 
    } 

问候,迪马。

0
void gvShowFullDetail_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#AECD6F"); 
     } 
    }