如何基于条件语句更改gridview单元格的背景颜色? [英] How can I change the background color of a gridview cell, based on a conditional statement?

查看:251
本文介绍了如何基于条件语句更改gridview单元格的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我显然没有给google正确的查询,或者我现在会发现。我希望在这个论坛上有人可以帮助我。

Okay I clearly haven't fed google the right query or I would've found out by now. I'm hoping someone on this forum can help me.

所以我有一个datatable,我添加行基于一个datareader从sql获取其信息在数据库上执行查询。到现在为止还挺好。现在,这些列之一被称为分析,如果前两列匹配,我需要它的背景颜色为绿色,否则为红色。

So I have a datatable that I'm adding rows to based on a datareader that's getting its info from an sql query executed over a database. So far, so good. Now, one of those columns is called 'analysis', and I need its background color to be green if the preceding two columns are matched, and red otherwise.

如果我不能触摸背景颜色,我想插入一个特殊字符,任何不被解释为文本的JavaScript。

If I can't touch the background color, I'd like to insert a special character, any javascript that isn't interpreted as text.

简单地说,我想css控制来自codebehind的gridview。我看了看,没有用。我找到了这个的人,但我避而不谈没有检查他的解决方案是否在ASP.Net/C#网站上工作。任何想法?

Simply put, I'd like css control over a gridview from codebehind. I've looked and looked to no avail. I found this guy, but I haven't checked if his solution works on an ASP.Net/C# website. Any ideas?

推荐答案

GridView_RowDataBound 事件中,获取要更改的单元格,颜色,如果您的条件测试为true,则设置单元格的颜色。

In the GridView_RowDataBound event, get the cell you want to change the back-color, set the color of the cell if your condition is tested 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单元格的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆