views:

1802

answers:

3

Say I have a DataGridView which shows the content of a DataTable.

I want to be able to set the backcolor of a row based on the value of a cell in this row.

Note that the cell in question is in a column which is not displayed in the DataGridView (Visible=False).

+1  A: 

If you handle the RowDataBound event you can check the value of the data and modify the attributes of the cell or apply a different style in that event handler.

protected void Page_Load(object sender, EventArgs e)
{
    GridView g1 = new GridView();
    g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}

void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
     // Check the Value
     if(e.Row.Cells[1].Text = someValue)
     {
      e.Row.Cells[1].CssClass = "colorCellRed";
     }

    }
}

That should give you what you are looking for. Let me know if you need it in VB rather than C#.

Good Luck!

Jason Stevenson
+1  A: 

RowDataBound, as already mentioned; you can also check the values of your data objects, as well as the text in the grid itself:

void gridView_DataBound(object sender, GridViewEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    var myObject = (myObject)e.DataItem;
    if (myObject.IsOverdue())
    {
      e.Row.CssClass = "overdue";
    }
  }
}
Keith Williams
A: 

Another option would be to use the CellFormatting event. First option shows accessing the bound data item and is useful if you don't have a column set up for the data in question. Second option works if there is a column whether it is visible or not.

    private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (((MyDataObject)dataGridView.Rows[e.RowIndex].DataBoundItem).Condition == Value)
            {
                e.CellStyle.BackColor = System.Drawing.Color.Gold;

            }
        }

// Option two -- can use ColumnIndex instead of ColumnName

    private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView["ColumnName", e.RowIndex].Value).Condition == TargetValue)
            {
                e.CellStyle.BackColor = System.Drawing.Color.Gold;

            }
        }
Mr.Mindor