在不更改边框颜色的情况下更改GridView单元格中文本的颜色

时间:2014-04-30 11:01:30

标签: c# asp.net css gridview

我在gridview中显示数据,并希望有条件地更改单元格中文本的颜色。

所以在网格的RowDataBound

if (e.Row.RowType == DataControlRowType.DataRow)
{
     if (((SurveyListHeader)(e.Row.DataItem)).PositionalConfidence != "G1" && ((SurveyListHeader)(e.Row.DataItem)).PositionalConfidence != "G3")
     {
          e.Row.Cells[3].ForeColor = System.Drawing.Color.Red;
        //e.Row.Cells[3].BorderColor = System.Drawing.Color.Black;
     }

     if (((SurveyListHeader)(e.Row.DataItem)).PositionalConfidence != "G2" && ((SurveyListHeader)(e.Row.DataItem)).PositionalConfidence != "G3")
     {
          e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
        //e.Row.Cells[4].BorderColor = System.Drawing.Color.Black;
     }
}

然而,这会导致边框颜色也发生变化。

enter image description here

我尝试将边框颜色更改为黑色,但这不起作用 我已经尝试将样式项添加到单元格的CSSStyleCollection中,但仍然没有乐趣。

我见过其他人遇到过这个问题,但没有回答对我有用。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

我已经使用了将边框颜色填充为黑色然后变为红色,然后我使用了else块来填充未更改为红色的单元格的黑色...它工作得很好。在这里我们可以使用任何细胞数。我用“3”作为例子。

if (e.Row.RowType == DataControlRowType.DataRow)
 {

                if (e.Row.Cells[3].Text.StartsWith("-"))
                {

                    // change the color
                    e.Row.Cells[3].BorderColor = System.Drawing.Color.Black;
                    e.Row.Cells[3].ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    e.Row.Cells[3].BorderColor = System.Drawing.Color.Black;
                }
}

答案 1 :(得分:1)

对于遇到这种情况的其他任何人,您可以通过更改前景色然后将所有边框更改为黑色来实现此功能 - 可能并不理想,但更改所有单个标签将是一场噩梦。下面的代码(请注意,您必须更改每个单元格而不仅仅是行边框)grdSearchResults是您的gridview:

 protected void grdSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {    
                if (e.Row.Cells[1].Text == "Closed")
                {
                    e.Row.ForeColor = System.Drawing.Color.LightGray;

                    for (int i = 0; i < grdSearchResults.Columns.Count; i++)
                    {
                        e.Row.Cells[i].BorderColor = System.Drawing.Color.Black;
                    }                 
                }    
            }
        }

答案 2 :(得分:0)

我在CSS中设置了边框颜色,并且在除firefox之外的几乎所有浏览器中都不会像您的代码那样更改边框。

.Gridview td
{
    border-right: lightsteelblue 1px solid;
    border-top: lightsteelblue 1px solid;
    border-left: lightsteelblue 1px solid;
    border-bottom: lightsteelblue 1px solid;
}
相关问题