Changing gridview cell foreground color

(ASP.NET)


Hi,
In this article i am changing the color of the gridview cell based on its value. While binding the employee details to the gridview. I am checking the score of employee, if its below 50, I change the color to red otherwise i change it to green.

.aspx page

 <div>
        <asp:GridView ID="grdvw_employee" OnRowDataBound="grdvw_employee_RowDataBound" runat="server">

        </asp:GridView>
    </div>


Code behind file

 public partial class differentrowColor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    bindgridView();
                }
            }
            catch (Exception)
            { }
        }

        private void bindgridView()
        {
            try
            {

                SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwindconstring"].ToString());

                List<Employee> lst = new List<Employee>();
                lst.Add(new Employee { empid = 1, EmployeeName = "Giri", Score = 90 });
                lst.Add(new Employee { empid = 2, EmployeeName = "Watson", Score = 40 });
                lst.Add(new Employee { empid = 3, EmployeeName = "Bala", Score = 80 });
                lst.Add(new Employee { empid = 4, EmployeeName = "Jim", Score = 45 });
            
                grdvw_employee.DataSource = lst;
                grdvw_employee.DataBind();

            }
            catch (Exception)
            { }
        }

        protected void grdvw_employee_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    int score = Convert.ToInt32(e.Row.Cells[2].Text);
                    //if the score of employee less than 50 change the font color to red
                    //else change the font color to green
                    if (score < 50)
                        e.Row.Cells[2].ForeColor = Color.Red;
                    else
                        e.Row.Cells[2].ForeColor = Color.Green;
                }
            }
            catch (Exception)
            { }
        }

    }

    
    public class Employee
    {
        public int empid { get; set; }
        public string EmployeeName { get; set; }
        public int Score { get; set; }
    }

Image

Ratings


Average Rating: 5.00 by 3 users
Giri Prasad
6/20/2013
6/20/2013
Download PDF

Comments






jimmy

very nice