This is a migrated thread and some comments may be shown as answers.

How to Conditionally format the text in a cell to red in grid

2 Answers 608 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Paul
Top achievements
Rank 1
Paul asked on 01 Oct 2015, 05:54 PM

Situation

I would like to conditionally format the text in a cell in a grid to red depending on its value.

Example:

If the value is less than 0 then display the text in red.

Value

123.8  - no change to text font

0 - no change to text font

-123.8 change text font to red.

I would like to use the ClientTemplate on a bound column

Here is a sample of the grid's code:

columns.Bound(c => c.Adjusted_Appreciation).Title("Adjusted_Appreciation").Format("{0:c}").Width(150).ClientTemplate("# if (Adjusted_Appreciation > 0) {}; #");

columns.Bound(c => c.Adjusted_Appreciation).Title("Adjusted_Appreciation").Format("{0:c}").Width(150).ClientTemplate("# if (Adjusted_Appreciation > 0) {}; #");

 

What do i put in the {}?

Thanks

Corey

2 Answers, 1 is accepted

Sort by
0
Paul
Top achievements
Rank 1
answered on 01 Oct 2015, 06:43 PM

Okay so i am getting closer to my goal.. just now need to apply the currency formatting:

Here is what i have so far.

ClientTemplate
          ("# if (Adjusted_Appreciation < 0) { #" +
             "<div style='color:red'>" + "#= Adjusted_Appreciation #" + "</div>" +
            "# } else { #" +
                 "#= Adjusted_Appreciation #" +
                "# } #").Format("{0:c}");

This colors it red when needed.. but the .Format("{0:c}") no longer works

 

0
Paul
Top achievements
Rank 1
answered on 01 Oct 2015, 07:35 PM

Okay so i think i have this issue solved.  Hope this helps someone.

Here is the final code:

The ClientTemplate
 
("# if (Adjusted_Appreciation < 0) { #" + "<div style='color:red'>" + "#= toCurrency(Adjusted_Appreciation) #" + "</div>" +  "# } else { #" + "#= toCurrency(Adjusted_Appreciation) #" + "# } #");
 
The Javascript function toCurrency
 
    function toCurrency(num) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '(') + '$' + num + '.' + cents + ((sign) ? '' : ')'));
    }

Tags
Grid
Asked by
Paul
Top achievements
Rank 1
Answers by
Paul
Top achievements
Rank 1
Share this question
or