views:

70

answers:

2

I have a griview which is bounded to a sqldatasource and changed dynamically. How do I change the background cell color based on the value? e.g., 0-0.5 green, 0.5-1 red, sth like that.

   <asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource3">
+1  A: 

One solution is to create a server method that you can call during databind, that will return a css class name.

Bind the css class attribute to a call to this method, and pass in the appropriate data element.

This is an example of the concept, you'd have to adapt it for your uses.

... Css file

.NegativeMoneyText
{
    color: #FF0000;
}

... Aspx file

<asp:Label ID="lblPaid" runat="server" CssClass='<%# getMoneyCssClass(Eval("PAID_AMOUNT").ToString()) %>' Text='<%# formatMoney(Eval("PAID_AMOUNT").ToString()) %>'></asp:Label>

... Code behind

public string getMoneyCssClass(string amount)
{
    if (!string.IsNullOrEmpty(amount))
    {
        double val = double.Parse(amount);
        if (val < 0)
            return "NegativeMoneyTextCss";
    }
    return return "PositiveMoneyTextCss";
}
asawyer
+2  A: 

You probably want to use the RowDataBound event of the GridView, something like this:

<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False" 
     DataSourceID="SqlDataSource3" OnRowDataBound="ChangeRowColor">

protected void ChangeRowColor(object sender, GridViewRowEventArgs e)
{
   if( ((DataRow)e.Row.DataItem)[1] == .5)
   {
     e.Row.Cell[1].BackColor = Colors.Green;
   }
}

In my example, I'm assuming the data used to fill the grid are DataRows (i.e. from a datatable), but essentially the idea is to cast the DataItem of the current row to whatever type of object is being bound to, check the value of the property you need, and then set the BackColor of the corresponding cell.

You could also inspect the Cell's text property, but you might have to do extra parsing or what-not to get from the string to whatever value you want to compare.

Coding Gorilla