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

时间:2012-04-10 17:36:12

标签: asp.net gridview

我的GridView有3个绑定列:A,B和C.我想在粗体中显示3列的最高值。如何进行比较并将字体设置为粗体(最好是在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列中的任何NUMERIC值都可以是最大值,具体取决于行。这是我想要设置为粗体的值。

示例:

3   **4**    1
**6**   2    0
**9**   1    2

3 个答案:

答案 0 :(得分: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");
        }
    }

答案 1 :(得分:6)

你需要代码隐藏这种东西。为此目的使用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;
    }
}

答案 2 :(得分:4)

您可以在gridview的rowdatabound方法中执行此操作。 理想的方法是从DB本身获得3个coloumns的最大值,并检查rawdatabound中的值。 这个网址可以帮助您提供一个小介绍。与此类似,您可以添加条件并将该列的相应字体样式设置为粗体 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx  在这种情况下你可以写这一行来加粗 e.Row.Cells[2].Font.Bold = true;