如何动态地为GridView单元格设置样式?

5

我的GridView有三个绑定列:A,B和C。我想显示这三列中的最高值,并以粗体方式显示。如何进行比较并设置字体为粗体(最好在aspx文件中)?谢谢。

<Columns>                
<asp:BoundField DataField="A" HeaderText="A" SortExpression="A" />                
<asp:BoundField DataField="B" HeaderText="B" SortExpression="B" />
<asp:BoundField DataField="C" HeaderText="C" SortExpression="C" />
</Columns>

为了澄清:根据行的不同,A、B和C列中的任何数值都可能是最大值。这就是我想要加粗显示的值。
例如:
3   **4**    1
**6**   2    0
**9**   1    2

1
“最高”值是什么?这些是数字字段吗?你的数据源是什么? - Tim Schmelter
3个回答

10

试一下这种方式:

   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        for (int j = 0; j < e.Row.Cells.Count; j++)
        {
            e.Row.Cells[j].Style.Add("BORDER-BOTTOM", "#aaccee 1px solid");
            e.Row.Cells[j].Style.Add("BORDER-RIGHT", "#aaccee 1px solid");
            e.Row.Cells[j].Style.Add("padding-left", "5px");
        }
    }

6

您需要使用CodeBehind进行此类操作。为此,请使用RowDataBound

protected void Grid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int number;
        var highestCells = e.Row.Cells.Cast<TableCell>()
            .Where(tc => int.TryParse(tc.Text, out number))
            .OrderByDescending(c => int.Parse(c.Text));
        foreach(var cell in highestCells)
            cell.Font.Bold = true;
    }
}

4
你可以在gridview的rowdatabound方法中完成此操作。 理想的方法是从数据库获取3个列的最大值,然后在rawdatabound中检查该值。此链接可帮助您提供简短的介绍。类似于此,您可以添加条件并将该列的相应字体样式设置为粗体。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx 在条件中,您可以编写以下代码使其加粗: e.Row.Cells[2].Font.Bold = true;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接