在DataGridView中更改特定单元格的前景色

时间:2013-08-19 06:12:12

标签: c# winforms datagridview

我正在尝试在datagridview中更改特定单元格的前景色。我想为同一行中的不同单元格赋予不同的颜色。

grid.Rows[row].Cells[col].Style.ForeColor = Color.Red

使用上述内容将更改所有行颜色,而不仅仅是我想要更改的单元格。

有没有办法单独改变特定细胞的颜色 - 不影响该行的其他细胞?

似乎我需要更改一些我不熟悉的Row属性。

4 个答案:

答案 0 :(得分:1)

如果在加载默认数据后立即应用Style或设置Row.DefaultStyle(datagridview.Datasource = Table), 在下次加载网格之前它不会受到影响。

(即如果你在加载事件中设置样式。它不会受到影响。但是如果你再次调用相同的函数,就像点击按钮之后它会起作用)

解决这个问题:

在DatagridView_DataBindingComplete事件中设置样式。它会正常工作并改变颜色你也可以

答案 1 :(得分:0)

  

使用上述内容将更改所有行颜色,而不仅仅是我想要更改的单元格

不,这不正确。它只会更改指定索引处单元格的文本颜色(Forecolor)。

您需要检查是否在代码中的其他位置设置了行的前景色。

以下代码适用于更改背面和前景色

//this will change the color of the text that is written
dataGridView1.Rows[0].Cells[4].Style.ForeColor = Color.Red;

//this will change the background of entire cell
dataGridView1.Rows[0].Cells[4].Style.BackColor = Color.Yellow;

答案 2 :(得分:0)

使用CellFormatting事件:

void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
   DataGridViewCell cell = grid.Rows[e.RowIndex].Cells[e.ColumnIndex];
   if (cell.Value is double && 0 == (double)cell.Value) { e.CellStyle.ForeColor = Color.Red; }
}

如果你能写出条件来找到特定的细胞。

或试试这个。

private void ColorRows()
   {
     foreach (DataGridViewRow row in dataGridViewTest.Rows)
     {
       int value = Convert.ToInt32(row.Cells[0].Value);
       row.DefaultCellStyle.BackColor = GetColor(value);
     }
   }

   private Color GetColor(int value)
   {
     Color c = new Color();
     if (value == 0)
       c = Color.Red;
     return c;
   }

   private void dataGridViewTest_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
   {
     ColorRows();
   }

答案 3 :(得分:-1)

你可以使用

dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = Color.Blue;
相关问题