Skip to content

Changing background color of individual datagrid cells

Adam Sta

Asked Mar 31, 2006, 4:42 AM EST4 answers
Share
LinkedInX
I have a Visual Studio Web application that I want to change individual datagrid cell colors depending on the data they hold.
Is there a way to change the background colors of individual cells in a datagrid using C#?

4 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Thanks for the link.  I checked it out.

    Its using C# Windows forms and not a C# web application...  I couldnt seem to get the code working in a Web App... 

    Is it possible to use similar code to this in a web app or would it be totally different? 
    0
  • 0
    To change the background of a cell in a WEB datagrid, it is best to do this at
    the ItemDataBound event. At that point just add an attribute to the cell

    Somthing like this will do:
    private void dg_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
       DataRowView row = (DataRowView)e.Item.DataItem;
       if(row["FieldName"].ToString == "Your Value")
       {
         e.Item.Cells[iColNum].Attributes.Add("style","your style");
       }
      }
    }
    0