Click here to Skip to main content
15,911,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

You can write the below code in RowDataBound event.
C#
 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;

            }
    }
}
 
Share this answer
 
v2
on Row_bound event of gridview use
C#
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;
          }
 
Share this answer
 
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
C#
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;
}
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900