Gridview row color change based on data asp.net c#

/ / 6 Comments

Codebehind change Gridview row color:   This article explains how to change Gridview row color based on data in Asp.net C#. For example in our Gridview we are displaying student report card information, .i.e `student name` and their `academic percentage`, now we want to highlight those record who got less than 35 % or greater than 75.

So based on data (condition) we change the background color of Gridview row in c# respectively. Here for merit we set green color, and for failed we set the red color.

You can also check Gridview related post .i.e.  Drag Drop to reorder GridView Rows,  Bind drop-down list inside Gridview edit template, and  Sorting Gridview control on header click with pagination.


# Html Markup:

First we are going to add asp.net Gridview control in our web page. So our HTML markup looks like as below.

//*
<asp:GridView ID="gvStudentGrade" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvStudentGrade_RowDataBound">
    <Columns>
        <asp:BoundField HeaderText="Sr no" DataField="srno" />
        <asp:BoundField HeaderText="Student Name" DataField="student_name" />
        <asp:BoundField HeaderText="Percentage" DataField="percentage" />
    </Columns>
</asp:GridView>
//*
 

# Code behind:

Here we bind data to our Gridview control. I have added a datatable with  some values ( data ) as  Student Name, Percentage.

Now set this datatable as our Gridview control datasource.

//*
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack) {
        bindGv_StudentGrade();
    }
}

public void bindGv_StudentGrade() {
    DataTable dtStudents = new DataTable();
    dtStudents.Columns.Add("srno", typeof(string));
    dtStudents.Columns.Add("student_name", typeof(string));
    dtStudents.Columns.Add("percentage", typeof(string));

    dtStudents.Rows.Add("1", "John Miller", "35");
    dtStudents.Rows.Add("2", "Amit Sarna", "85");
    dtStudents.Rows.Add("3", "David Macule", "75");
    dtStudents.Rows.Add("4", "Andrea ely", "60");
    dtStudents.Rows.Add("5", "Rohit Sharma", "20");
    dtStudents.Rows.Add("6", "Pamela Franz", "55");
    dtStudents.Rows.Add("7", "Leslie Mac", "92");
    gvStudentGrade.DataSource = dtStudents;
    gvStudentGrade.DataBind();
}
//*
[ads_468_60]

Now we are at the main part of this post:

Code how to set the different background color of Gridview row, based on data in Asp.net C#. For this, we use `GridView.RowDataBound` Event this event Occurs when a data row is bound to data in a GridView control.

The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control.

This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.

 Gridview Row color change using GridView.RowDataBound Event

//*
protected void gvStudentGrade_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    int getValue = Convert.ToInt32(e.Row.Cells[2].Text);
    string setColorClass=string.Empty;
    if (getValue >= 75) {
        setColorClass = "successMerit"; // setting green color class 
     }
     else if (getValue <= 35)  {
         setColorClass = "dangerFailed"; // setting red color class
     }
     else {
        setColorClass = "defaultColor";
     }
     e.Row.CssClass = setColorClass;
   }
}
//*
 

In the above code  first we  fetch, the value from the third column and convert it into an integer  datatype, later we apply our condition.

Here in my case I am checking it if it's greater than 75, then set Gridview row background color as green, and if its less than 35, then set  row background color as red.

I have added a class to respected Gridview row, to make above code actually working we need to add those CSS class in our Asp.net Webpage (.aspx ) design page as shown below.

//*
<style type="text/css">
  .successMerit {
    background-color: #1fa756;
    border: medium none;
    color: White;
  }
    .defaultColor
    {
        background-color: white;
        color: black;
    }
  .dangerFailed {
    background-color: #f2283a;
    color: White;
  }
</style>
//*
 

Finally here's our output: Change Gridview control row background-color based on data.

[caption id="attachment_2656" align="aligncenter" width="300"]Gridview row color change based on data asp.net c# Gridview row color change based on data asp.net c#[/caption]   You must check these articles: Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

6 Comments

  1. Amit Kumar 09/16/2015 08:34:43
    Hi. I really liked this example. Actually my scenarios is similar to this. I am into sharepoint dev. my scenarion is to develop a gantt chart of tasks into gridview. Suppose a task is initiated on jan 1, 2015 and goes upto mar 1, 2015, it means 3 columns of grid view should be colored. I have taken 13 columns in grid view. 1st col for task and rest 12 col for jan to dec month. It will not show any date. It will be just displayed as Jan, feb upto dec. Suppose if task initiated in fall month, then color from jan to mar (imagine) should be yellow. If it happens in summer task from apr to aug, then it should be colored as gray. Hence it will be display as a gantt chart. Pls provide solution. I m using sharepoint list to fetch data from list to grid view. all category of fall, summer are stored in sp list.
  2. Satinder singh 09/22/2015 16:49:51
    Hi amit, Thanks for the comment, well I haven't got chance to work with SharePoint so I can't give you proper solution, but will give a basic idea. As you generate 12 columns dynamically .i.e (Jan,Feb, so on...) so you can create a list of collection which holds the MonthName and Column index position , Based on data (database value) you can color specific column using column index
  3. Satinder singh 10/13/2016 06:26:56
    Hi Priti thanks for reading. Well you can achieve it by adding one extra column(dtfrom) to each DataTable .i.e for dt1 add value for newly added column (dtfrom) as 1 and for dt2 set value as 2. Then on GridView_RowDataBound event check the cell value and set your CSS Style by adding respective CSS class.
  4. Priti 10/13/2016 11:37:23
    Thank you Sir, this solved my query . I added extra column to dt but how do i hide it from displaying? Tried on Grid_Databound event this.GridView1.Columns[3].Visible = false; also autogenerate column property but it doesnt work. My Grid is generated from stored procedure .
  5. Satinder singh 10/13/2016 16:00:23
    Hiding specific cell can be done with simple CSS i.e using display:none; or you can set opacity:0 for that table cell
  6. Satinder singh 10/14/2016 11:56:39
    Great !