1. Back To Blog

.NET and ASP.NET interview questions: - Steps to change cells color of GridView according to some condition?

.NET and ASP.NET interview questions: - Steps to change cells color of GridView according to some condition?

This is not one of the typical .NET interview questions but on knowledge aspect it might be very helpful and also helpful while you dealing with GridView.

Let's do simple demonstration to see how exactly we can achieve this practically.

In order to achieve this practically just follow the following steps.

Step1: - create a simple ASP.NET Empty Web Application for that just Go To > File > New > Project > Select ASP.NET Empty Web Application.

Step2: - Now add a Web Form in your project for that just Go To > Solution Explorer > Right Click on the Project Name > Add > Add New Item > Select Web Form.

Step3: - Now just drag and drop GridView control to your Web Form.

Step4: - Now just create a method to bind the data to the GridView control as I have done in below code snippet and later just call that method on the form_load event.

protected void Page_Load(object sender, EventArgs e)

public void LoadGridView()

SqlConnection Con = new SqlConnection(ConnectionString);
SqlCommand Com = new SqlCommand();
Com.CommandText = "select * from Employee";
Com.Connection = Con;
SqlDataAdapter Adap = new SqlDataAdapter(Com);
DataSet ds = new DataSet();
GridView1.DataSource = ds;

Step5: - this is the most important step.

In this step just add RowDataBound event of the GridView control to theWebForm.aspx.cs file and add the below code snippet to change the color of the GridView cells according to some condition.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

if (e.Row.RowType == DataControlRowType.DataRow)

double Salary = Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem,"Emp_Salary")));
if (Salary > 10000)

e.Row.Cells[4].BackColor = System.Drawing.Color.Red;

e.Row.Cells[4].BackColor = System.Drawing.Color.Green;

In the above code snippet you can see that I have just created a variable called Salary as double which is containing the value of the Emp_Salary column and I have used that variable Salary to give some condition on which the color of the cell of GridView control is going to change.

As soon as you have completed all the above steps now just run your application you will see result like below diagram.

In the above result you can clearly see that now the cells color of the GridView has been changed according to the given condition.

View a video on Windows Authentication as follows: -

.NET and ASP.NET interview questions for preparation of real time interviews.


Get more from author's blogs for.NET and ASP.NET interview questions

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social