Sudheesh A P
Sudheesh A P

Reputation: 77

How can i change the color of particular row of a datagrid

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

Upvotes: 1

Views: 8909

Answers (4)

Prajin P V
Prajin P V

Reputation: 1

// For a Particular Cell

dataGridView1.Rows[RowIndex].Cells[ColumnIndex].Style.BackColor = Color.Red;

// For a Particular Row

dataGridView1.Rows[RowIndex].DefaultCellStyle.BackColor = Color.Black;

// For a Particular Column

dataGridView1.Columns[ColumnIndex].DefaultCellStyle.BackColor =Color.Yellow;

Upvotes: 0

Paul Keister
Paul Keister

Reputation: 13097

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.

Upvotes: 0

Kamran Khan
Kamran Khan

Reputation: 9986

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.

Upvotes: 2

Adam Houldsworth
Adam Houldsworth

Reputation: 64537

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.

Upvotes: 2

Related Questions