C# 更改DataGridView的行背景色
我搜索了很多,找到了一些在datagrid视图中更改行背景颜色的方法,但根本不起作用,你能帮我找到我的错误吗C# 更改DataGridView的行背景色,c#,datagridview,C#,Datagridview,我搜索了很多,找到了一些在datagrid视图中更改行背景颜色的方法,但根本不起作用,你能帮我找到我的错误吗 dataGridViewResult.DataSource = morgan.GetResult().Tables[5]; dataGridViewResult.Rows[0].Cells[1].Style.ForeColor = System.Drawing.Color.Beige; dataGridViewResult.Rows[0].DefaultC
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;
此代码可能会工作:
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;
}
更多信息:m.lansers的答案是正确的。您是否已将他使用的方法绑定到DataGridViews事件?例如:
dataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(grid1_CellFormatting);
此外,另一种较短的代码位是只使用:
e.CellStyle.BackColor = Color.Blue;
您发布的代码正在更改前景色,而不是背景色。这是你想要的吗?粘贴错误?旁注:您将第35行更改了两次,使第一次更改过度。@Ohbowise事实上我已经测试了大多数cellstyles,它们根本不工作。它没有显示任何错误,只是没有更改颜色。关于第35行是的,这是我的错误,但它没有更改anything@MajidHojati我检查了一下,它工作了。错误是什么?这不为行中找到的每个单元格设置行的颜色是什么?这意味着重复设置相同的值。