Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the row background color of DataGridView

I have searched a lot and found some methods to change a rows background color in datagrid view but it does not work at all,Can you help me find my mistake?

dataGridViewResult.DataSource = morgan.GetResult().Tables[5];
        dataGridViewResult.Rows[0].Cells[1].Style.ForeColor = System.Drawing.Color.Beige;
        dataGridViewResult.Rows[0].DefaultCellStyle.ForeColor = Color.Blue;
        dataGridViewResult.Rows[7].DefaultCellStyle.ForeColor = Color.Blue;
        dataGridViewResult.Rows[40].DefaultCellStyle.ForeColor = Color.Blue;
        dataGridViewResult.Rows[11].DefaultCellStyle.ForeColor = Color.Blue;
        dataGridViewResult.Rows[19].DefaultCellStyle.ForeColor = Color.Blue;
        dataGridViewResult.Rows[28].DefaultCellStyle.ForeColor = Color.Blue;
        dataGridViewResult.Rows[35].DefaultCellStyle.ForeColor = Color.Blue;

        dataGridViewResult.Rows[35].DefaultCellStyle.ForeColor = Color.White;
like image 646
Majid Hojati Avatar asked Oct 29 '25 05:10

Majid Hojati


2 Answers

This code might work:

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index
    // check the cell value under your specific column and then you can toggle your colors
    row.DefaultCellStyle.BackColor = Color.Green;
}

More info: DataGridView row's background color is not changing

like image 136
m.lanser Avatar answered Oct 31 '25 01:10

m.lanser


m.lansers answer is correct. Have you bound the method he used to the DataGridViews CellFormatting event? as in:

dataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(grid1_CellFormatting);

Additionally an alternative shorter bit of code would be to just use:

e.CellStyle.BackColor = Color.Blue;
like image 22
Matthew North Avatar answered Oct 31 '25 01:10

Matthew North