c# - 如何根据条件语句更改 gridview 单元格的背景颜色?

标签 c# css gridview code-behind

好吧,我显然没有向谷歌提供正确的查询,否则我现在就会发现了。我希望这个论坛上的人可以帮助我。

所以我有一个数据表,我要根据数据读取器向其添加行,该数据读取器从对数据库执行的 sql 查询中获取信息。到目前为止,一切都很好。现在,其中一列称为“分析”,如果前两列匹配,我需要它的背景色为绿色,否则为红色。

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

简单地说,我希望通过代码隐藏对 gridview 进行 css 控制。我看了又看都无济于事。我找到了 this家伙,但我还没有检查他的解决方案是否适用于 ASP.Net/C# 网站。有什么想法吗?

最佳答案

GridView RowDataBound 事件中,获取要更改背景色的单元格,如果条件测试为真,则设置单元格的颜色。

/// <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
        {
        }
    }
}

关于c# - 如何根据条件语句更改 gridview 单元格的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3146456/

相关文章:

c# - Activator.CreateInstance MissingMethodException 异常

c# - 无法在大于 10K 的 UDP 上发送图像

c# - 是否可以在同一个 asp.net 网站中使用 C# 和 vb.net?

html - 表格不需要的填充

C# - Selenium - 重试属性不适用于 Selenium 超时

javascript onmouseover+onmouseout 和 2 个 div 之间的关系

javascript - 裁剪掉图像中的所有白色

c# - ASP.NET:何时以及如何在代码后面动态更改 Gridview header 文本?

android - 我的 customarayadapter 似乎传递了错误的变量

android - 如何在 XML 中填充 gridview