C#DataGridView单行颜色文本

nei*_*man 3 c# coding-style datagridview

我有一个DataGridView,它有一个类作为其DataSource.

该类包含一个ID字符串,2x DateTimes和一个布尔值.

我已经编写了一些代码来更改与我传递给方法的ID相匹配的行的文本,但是我没有尝试过.

这是我到目前为止:

public void ShowInstanceAsTerminated(String id)
{
    foreach (DataGridViewRow dgvRow in dgvRIM.Rows)
    {
        if (dgvRow.Cells[0].Value.ToString() == id)
        {
            dgvRow.DefaultCellStyle.ForeColor = Color.Red;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试的代码的众多变体之一,但问题的细胞永远不会改变!

谢谢尼尔

Eri*_* J. 13

试试这种格式:

dgvRIM.Rows[myRow].Cells[0].Style.ForeColor = Color.Red;
Run Code Online (Sandbox Code Playgroud)

如果要设置整行,请遍历所有单元格.


Jay*_*ggs 5

使用DataGridView的CellFormatting事件对组成行的单个单元格进行更改.

像这样的东西(小心,未经测试):

private void dgvRIM_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
  if (dgvRIM.Rows[e.RowIndex].Cells[0].Value.ToString() == id) {
    e.CellStyle.ForeColor = Color.Red;
  }
}
Run Code Online (Sandbox Code Playgroud)