Wednesday, April 13, 2011

How do I Turn negative numbers red?

I am working with a dataset, and will be returning both positive and negative currency figures. I already have a parenthesis around it. How do I get only the negative numbers in the gridview to show up in red? Can I do this on the HTML side?

From stackoverflow
  • There are many ways to do this, two spring to mind:

    1. Apply a CSS class that will set the element's color to red.
    2. Set the Color property on the WebControl you are using to render the number.

    Without some code it will be difficult to give you specific examples.

  • Without going to a third party control that has formatting rules, I would use the Row's data binding event and color the text of the cell in question when it is negative. This adds a slight bit of weight to the UI layer, but not enough it will be noticeable until you are delivering thousands and thousands of rows. If you are delivering thousands and thousands of rows, you probably have an architecture problem.

  • I would set the CssClass of the control to something that styles the text the way you want if the number is negative. The reason for using CssClass instead of FontColor is that you may change this in the future and it will be easier to just change the CSS style rather than any code that uses it.

    <asp:BoundField runat="server"
        DataField="Value"
        HeaderText="value"
        ItemStyleCssClass='<% (double)Eval("Value") < 0 ? "negative-number" : "" %>' />
    
  • protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)    {
    
       myCell = new TableCell();       
       myCell.Text =   e.Row.DataItemIndex.ToString();
       myCell.Style["color"] = decimal.Parse(myCell.Text)<0?"Red":"OtherColor";
       e.Row.Cells.Add(myCell);
    
    
    }
    

    or something like that

  • You could try styling with jQuery:

    jQuery:

    $("span:contains('-')").css("color", "#f00");
    

    Of course, change span for whatever tag your number is in (and consider going into something more specific than just span like span.number-container for example.

0 comments:

Post a Comment