You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET GridView条件格式化运行正常但无颜色效果问题求助

问题解决方法

1. 未绑定RowDataBound事件

你编写的行绑定方法没有和GridView控件关联,数据行绑定时不会触发对应逻辑,是最常见的失效原因。
修改GridView标签,添加事件绑定属性即可:

<asp:GridView
  id="GridView2"
  runat="server"
  AllowSorting="True"
  OnRowDataBound="GridviewRowDataBound"
  DataSourceID="AccessDataSource1" 
  Caption="Trained Purchased" 
  PageSize="25" 
  AutoGenerateColumns="False">

2. 后台代码语言与页面声明不匹配

你页面头部声明为<%@ Page Language="VB" CodeBehind="TrainPurch.aspx.vb" %>,说明后台使用VB.NET语法,但你贴的后台方法是C#语法,两种语言不兼容。要么将页面Language属性改为C#,要么将后台方法改为VB.NET版本:

Protected Sub GridviewRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim CellValue As Integer = Convert.ToInt32(e.Row.Cells(2).Text)
        If CellValue >= 0 Then
            e.Row.Cells(2).BackColor = System.Drawing.Color.Green
        Else
            e.Row.Cells(2).BackColor = System.Drawing.Color.Red
        End If
    End If
End Sub

3. 兼容空值/格式异常避免逻辑中断

如果Units字段可能为空、带空格或非数字内容,直接转int会抛出异常导致行绑定中断,建议添加校验逻辑:
C#优化版本:

protected void GridviewRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if(int.TryParse(e.Row.Cells[2].Text?.Trim(), out int CellValue))
        {
            e.Row.Cells[2].BackColor = CellValue >= 0 ? System.Drawing.Color.Green : System.Drawing.Color.Red;
        }
    }
}

VB优化版本:

Protected Sub GridviewRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim CellValue As Integer
        If Integer.TryParse(e.Row.Cells(2).Text?.Trim(), CellValue) Then
            e.Row.Cells(2).BackColor = If(CellValue >= 0, System.Drawing.Color.Green, System.Drawing.Color.Red)
        End If
    End If
End Sub

4. 排查样式覆盖问题

如果修改后仍不生效,打开浏览器开发者工具选中目标单元格,查看样式属性,确认是否有全局CSS、GridView主题样式覆盖了BackColor属性。如果存在覆盖可以给单元格添加自定义CssClass,用优先级更高的样式控制背景色。

内容的提问来源于stack exchange,提问作者ctodad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:09:01