Friday, 11 January 2013

Change GridView row color based on condition in C# (GridView.RowDataBound Event)

 protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string value = "";
        string value2 = "";
        double cval;
        double sval;
        double color;
        double round;
        double reversal;
     
        value = e.Row.Cells[4].Text.ToString().Trim();
        value2 = e.Row.Cells[3].Text.ToString().Trim();

        if (value != " " && value != "" )
        {
            if(value == "0" && value2 != "0" )
            {
                e.Row.Cells[1].Style.Add("background-color", "GREEN");
                e.Row.Cells[2].Style.Add("background-color", "GREEN");
            }

            else if( value != "0" && value2 == "0")
            {
                e.Row.Cells[1].Style.Add("background-color", "PURPLE");
                e.Row.Cells[2].Style.Add("background-color", "PURPLE");
            }

            else
            {
            cval = Convert.ToDouble(value);
            sval = Convert.ToDouble(value2);

            color = cval / sval * 100;
            round = Math.Round(color);
            reversal = cval - sval;
             

            if (round <= 25)
            {
                e.Row.Cells[1].Style.Add("background-color", "GREEN");
                e.Row.Cells[2].Style.Add("background-color", "GREEN");
            }

            else if (round > 25 && round <= 50)
            {
                e.Row.Cells[1].Style.Add("background-color", "BLUE");
                e.Row.Cells[2].Style.Add("background-color", "BLUE");
            }
            else if (round > 50 && round < 75)
            {
                e.Row.Cells[1].Style.Add("background-color", "ORANGE");
                e.Row.Cells[2].Style.Add("background-color", "ORANGE");
            }

            else if (round >= 75)
            {
                e.Row.Cells[1].Style.Add("background-color", "RED");
                e.Row.Cells[2].Style.Add("background-color", "RED");
            }
        }
        }    
    }

No comments:

Post a Comment