其他分享
首页 > 其他分享> > 我如何根据条件语句更改gridview单元的背景颜色?

我如何根据条件语句更改gridview单元的背景颜色?

作者:互联网

好吧,我显然没有为Google提供正确的查询,或者我现在已经找到了.我希望这个论坛上的人可以帮助我.

所以我有一个数据表,我正在根据一个数据读取器向其中添加行,该数据读取器是从在数据库上执行的sql查询中获取其信息的.到现在为止还挺好.现在,这些列之一称为“分析”,如果前两列匹配,我需要将其背景色设为绿色,否则将其设为红色.

如果我无法触摸背景颜色,则想插入一个特殊字符,即任何不能解释为文本的javascript.

简而言之,我想从代码背后通过CSS控制gridview.我看了看,没用.我找到了this个人,但是我没有检查他的解决方案是否在ASP.Net/C#网站上有效.有任何想法吗?

解决方法:

在GridView_RowDataBound事件中,获取要更改背景色的单元格,如果条件被测试为true,则设置该单元格的颜色.

/// <summary>
/// Handles gridview row data bound event.
/// </summary>
/// <param name="sender">Sender Object</param>
/// <param name="e">Event Argument</param>
protected void Gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // We don’t want to apply this to headers.
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        try
        {
            //your data-object that is rendered in this row, if at all required.
            //Object obj = e.Row.DataItem;

            //find the right color from condition
            string color = condition ? "#ff9900" : "some-other-color";

            //set the backcolor of the cell based on the condition
            e.Row.Cells[4].Attributes.Add("Style", "background-color: " + color + ";");
        }
        catch
        {
        }
    }
}

标签:gridview,code-behind,css,c
来源: https://codeday.me/bug/20191210/2098108.html