Click here to Skip to main content
14,599,019 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi,
I have one gridview and records are like this

Hid emp -----
-------------------
12 abc -----
12 ---
12 ---
12 ---
13
13
13
14
14
14

Now i want different colors for different unique Hid's. For suppose i want
12-red
13-yellow
14-green



How?
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 3

You can write the below code in RowDataBound event.
 void gridview1_RowDataBound(object sender, 
  GridViewRowEventArgs e)
{
    var gridview1 = sender as GridView;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
            string id = gridview1.DataKeys[e.row.RowIndex]["Hid"].ToString();
            switch (id)
            {
                case 12:
                e.row.BackColor = Color.Red;
                break;
                case 13:
                e.row.BackColor = Color.Yellow;
                break;
                case 14:
                e.row.BackColor = Color.Green;
                break;

            }
    }
}
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

on Row_bound event of gridview use
if (e.Row.Cells[0].Text == "12")
          {
              e.Row.Cells[0].ForeColor = System.Drawing.Color.Red;
          }
else if(e.Row.Cells[0].Text == "13")
          {
              e.Row.Cells[0].ForeColor = System.Drawing.Color.Yellow;
          }
   
Comments
Member 8609405 26-Jun-12 8:27am
   
i dont no the data
Member 8609405 26-Jun-12 8:27am
   
I am getting data from database
uspatel 26-Jun-12 8:31am
   
then on what condition you want to change color?
uspatel 26-Jun-12 8:32am
   
You can set any logic like even id's have color red odd have yellow or any.
Member 8609405 26-Jun-12 8:36am
   
thanks
Rate this:
Please Sign up or sign in to vote.

Solution 4

private void dgr_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    string testValue = dgr.Rows[e.RowIndex].Cells[0].Value.ToString();
    Color setColor = dgr.Rows[e.RowIndex].DefaultCellStyle.BackColor;

    switch (testValue)
    {
        case "12":
            setColor = Color.Red;
            break;
        case "13":
            setColor = Color.Yellow;
            break;
        case "14":
            setColor = Color.Green;
            break;
        default:
             break;
    }

    dgr.Rows[e.RowIndex].DefaultCellStyle.BackColor = setColor;
}
   
v2
Comments
DimLifeAsShort 26-Jun-12 8:42am
   
sorry, my quick solution is for winforms datagridview, not the aspx control.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100