tags:

views:

46

answers:

3

i am going to bind a datatable to the datagrid i just want to change the color of a particular row of datagrid based on the value on datatable row. i need c#/.net code for it

+2  A: 

The grid view features a sort of hierarchy of properties that control style. A good overview is here:

http://msdn.microsoft.com/en-us/library/1yef90x0.aspx

But most simply, you can likely set the DataGridViewRow.DefaultCellStyle.BackColor property for unselected rows and the DataGridViewRow.DefaultCellStyle.SelectionBackColor property for selected rows.

Adam
I think you mean SelectionBackColor, not BackColor, which will set the background color of rows that are *not* selected.
Paul Keister
@Paul good spot. It's early in the morning and I hadn't spotted that in the question :)
Adam
i am going to bind a data table to the datagrid.
Sudheesh A P
i just want to change the color of a particular row of datagrid based on the valulue on datatable row. i need c#/.net code for it
Sudheesh A P
+1  A: 

Something like:

this.dataGridView1.Rows[RowIndex].DefaultCellStyle.BackColor = Color.Yellow;

Or if you want to it over a mouse move event

private void DataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
}

private void DataGridView_CellLeave1(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Blue;
}

Also, Change individual DataGridView row colors based on column value might help.

KMan
A: 

If you want to change the appearance of selected rows based on the contents of the rows rather than the selection state, this is how I'd do it:

   private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (RowShouldBeRed(e))
        {
            e.CellStyle.BackColor = Color.LightPink;
            e.CellStyle.SelectionBackColor = Color.Red;
        }
        else
        {
            e.CellStyle.BackColor = DataGridView1.DefaultCellStyle.BackColor;
            e.CellStyle.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor;
        }
    }

In this example, the RowShouldBeRed funciton is a stub for the logic you would use to determine how to color the row.

Paul Keister