Change cell color in gridview depending the inner value
As long time reader ;-) of my blog you know: i am fan of the declarative ASP.NET way ( especialy 2.0) But sometimes i reach the limits. This is e.g. for changing font color in a cell if a value reaches limits (negativ). For this purpose you can use rowcreated event of the gridview.
- take care on rowtype
- Findcontrol with e.row.cell(0) or findcontrol
- access underlaying data with e.row.dataitem
- take care on datatype (this example decimal)
Now the complete code. It based on a templatefield with a label inside.
Protected
Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow ThenDim lbl As Label = CType(e.Row.FindControl("lblPreis"), Label)
If DataBinder.Eval(e.Row.DataItem, "unitprice") < 0D Then
lbl.ForeColor = Drawing.Color.Red End If End If End Sub
Hope this helps!