.NET and ASP.NET interview questions: - Steps to change cells color of GridView according to some condition?
- By Shiv Prasad Koirala in ASP.NET
- Sep 14th, 2011
- 7595
- 0
.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) LoadGridView(); } public void LoadGridView() SqlConnection Con = new SqlConnection(ConnectionString); Con.Open(); SqlCommand Com = new SqlCommand(); Com.CommandText = "select * from Employee"; Com.Connection = Con; SqlDataAdapter Adap = new SqlDataAdapter(Com); DataSet ds = new DataSet(); Adap.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); }
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; } else 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.
Regards,
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