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

3 posts, 0 answers
  1. Corey
    Corey avatar
    13 posts
    Member since:
    Sep 2015

    Posted 01 Oct 2015 Link to this post

    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. Corey
    Corey avatar
    13 posts
    Member since:
    Sep 2015

    Posted 01 Oct 2015 Link to this post

    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

     

  3. UI for ASP.NET MVC is VS 2017 Ready
  4. Corey
    Corey avatar
    13 posts
    Member since:
    Sep 2015

    Posted 01 Oct 2015 Link to this post

    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) ? '' : ')'));
        }

Back to Top