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

如何在C#中将GridView最后一行文本设置为加粗样式?

解决GridView最后一行文本加粗的问题

你已经通过RowDataBound事件精准定位到了目标行(sName为"TOT"的行),还成功设置了背景色,其实你代码里写的e.Row.Font.Bold = true;逻辑是对的,可能是被样式覆盖导致没生效?我来给你梳理下可行的解决方案,帮你搞定这个问题:

方案一:用CSS类控制(优先级更高,推荐)

如果GridView的行或单元格有预设的CSS样式,很可能会覆盖后台代码设置的Font属性,这种情况下用CSS类更稳妥:

  1. 先在页面的样式区域定义一个样式类:
    .summary-row {
        font-weight: bold !important;
        font-style: italic;
        background-color: gainsboro;
    }
    
  2. 然后在RowDataBound事件里替换原有代码,给目标行添加这个类:
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 
        if (e.Row.RowType == DataControlRowType.DataRow) { 
            if (((string)DataBinder.Eval(e.Row.DataItem, "sName")).Equals("TOT")) { 
                e.Row.CssClass = "summary-row";
            }
        }
    }
    

方案二:遍历单元格单独设置样式

如果整行设置不生效,也可以逐个给单元格设置样式,避免被整体样式覆盖:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 
    if (e.Row.RowType == DataControlRowType.DataRow) { 
        if (((string)DataBinder.Eval(e.Row.DataItem, "sName")).Equals("TOT")) { 
            e.Row.BackColor = Color.Gainsboro;
            // 遍历每个单元格,单独设置字体样式
            foreach (TableCell cell in e.Row.Cells)
            {
                cell.Font.Bold = true;
                cell.Font.Italic = true;
            }
        }
    }
}

小提示:排查原有代码不生效的原因

大概率是样式优先级的问题——GridView的主题、控件自带样式或者页面全局CSS,优先级比后台代码设置的Font属性高,导致加粗效果被覆盖。用上面两种方法都能有效规避这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:38:54