【问题标题】:How to style a GridView cell dynamically?如何动态设置 GridView 单元格的样式?
【发布时间】:2012-04-11 02:47:51
【问题描述】:

我的 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

【问题讨论】:

  • 什么是“最高”值?这些是数字字段吗?你的数据源是什么?

标签: asp.net gridview


【解决方案1】:

试试这个方法:

   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");
        }
    }

【讨论】:

    【解决方案2】:

    您需要代码隐藏来处理这类事情。为此目的使用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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以在 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;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-16
        • 2017-02-01
        相关资源
        最近更新 更多