Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style a GridView cell dynamically?

My GridView has 3 bound columns: A, B, and C. I want to display the highest value of the 3 columns in bold. How do I do the comparison and set the font to bold (preferably in the aspx file)? Thanks.

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

To clarify: any of the NUMERIC values in columns A, B and C can be the biggest depending on the row. This is the value I want to set to bold.

Example:

3   **4**    1
**6**   2    0
**9**   1    2
like image 992
RJIGO Avatar asked Apr 10 '12 17:04

RJIGO


2 Answers

Try this way:

   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");
        }
    }
like image 144
coder Avatar answered Sep 27 '22 22:09

coder


You need codebehind for this sort of thing. Use RowDataBound for this purpose:

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;
    }
}
like image 27
Tim Schmelter Avatar answered Sep 27 '22 21:09

Tim Schmelter