Setting gridview row background colour by alternating by row data type

1k views Asked by At

I have a GridView where I am listing values for client companies. Take for example the grid listed the company name and a value. I want to give a light gray background color to all Company 1's rows, then white for Company 2's rows and then back to light grey for Company 3's rows and alternating like so.


Company 1 12

Company 1 15

Company 1 18


Company 2 25

Company 2 78

Company 2 109


Company 3 66

Company 3 1


Can this be done simply in the _RowDataBound event, and if so how?

2

There are 2 answers

0
Paul Kirkason On BEST ANSWER

I managed to use this question

alternate color gridview rows based on change of cell value asp.net

to create my own solution in c#. So basically, create two global variables. Then within the _RowDatabound do the below

int customerCompanyID = Convert.ToInt32(dr["IRPCustomerID"]);

 if (customerCompanyID != this._trafficSourceGridCurrentCompanyID)
            {
                if (this._trafficSourceGridGroupingCssClass == 
"BackGround2")
                {
                    this._trafficSourceGridGroupingCssClass = "BackGround1";
                }
                else
                {
                    this._trafficSourceGridGroupingCssClass = "BackGround2";
                }

                this._trafficSourceGridCurrentCompanyID = customerCompanyID;                    
            }

            e.Row.CssClass = _trafficSourceGridGroupingCssClass;
0
AudioBubble On

In RowDataBound event you can do something like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // check if its not a header or footer row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // get value from first cell of gridview
        string companyName = e.Row.Cells[0].Text;

        switch (companyName)
        {
            case "Company 1":
                e.Row.BackColor = System.Drawing.Color.LightGray;
                break;
            case "Company 2":
                e.Row.BackColor = System.Drawing.Color.White;
                break;
            case "Company 3":
                e.Row.BackColor = System.Drawing.Color.LightGray;
                break;
            default:
                break;
        }
    }
}