更改DataGridView的行背景颜色

时间:2015-02-14 12:41:26

标签: c# datagridview

我搜索了很多并找到了一些方法来改变数据网格视图中的行背景颜色,但它根本不起作用,你能帮我找到我的错误吗?

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;

2 个答案:

答案 0 :(得分:1)

此代码可能有效:

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;
}

更多信息:DataGridView row's background color is not changing

答案 1 :(得分:1)

m.lansers回答是正确的。您是否将他使用的方法绑定到DataGridViews CellFormatting事件?如:

dataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(grid1_CellFormatting);

另外,可以使用另一个较短的代码:

e.CellStyle.BackColor = Color.Blue;