DataGridView更改单元格背景颜色

Rém*_*émi 14 c# datagridview winforms

我有以下代码:

private void dgvStatus_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dgvStatus.Rows)
    {
        row.Cells[color.Index].Style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图从背景颜色列设置每个单元格的背景颜色.这不起作用颜色永远不会改变.知道为什么吗?

我一直在环顾四周,但没有找到任何有用的东西

Jeb*_*Jeb 27

只需创建一个新的DataGridViewCellStyle对象,设置其背景颜色,然后为其指定单元格的样式:

    DataGridViewCellStyle style = new DataGridViewCellStyle();
    style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
    style.ForeColor = Color.Black;
    row.Cells[color.Index].Style = style;
Run Code Online (Sandbox Code Playgroud)


Rém*_*émi 15

我终于设法让它工作了.这里的代码:

private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex != color.Index)
        return;

    e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString()));
}
Run Code Online (Sandbox Code Playgroud)

如果有人知道这样做更好,请不要犹豫发布.我愿意接受建议

  • 看起来您正在使用以下“动态设置样式”部分中概述的方法:http://msdn.microsoft.com/en-us/library/1yef90x0.aspx,我之前来自@EJC 的链接的回答引用了该方法。 (2认同)

Ysc*_*sch 11

如果您仍然感兴趣,为什么这对您起初不起作用:

您没有看到对单元格样式所做的更改的原因是您显示表单之前执行了这些更改,因此忽略它们.

在这里建议的事件中更改单元格样式将完成这项工作,但它们被多次调用,导致您的样式更改发生的次数超出您的预期,因此效率不高.

要解决此问题,请在显示表单的代码中的点之后更改样式,或者订阅Shown事件,并将更改放在那里(这个事件的调用明显少于建议的其他事件).


小智 6

dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGreen;
Run Code Online (Sandbox Code Playgroud)


小智 6

int rowscount = dataGridView1.Rows.Count;         

for (int i = 0; i < rowscount; i++)
{            
    if (!(dataGridView1.Rows[i].Cells[8].Value == null))
    {
        dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
    }
}
Run Code Online (Sandbox Code Playgroud)