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

本文关键字:单元格 前景色 DataGridView 更改 | 更新日期: 2023-09-27 18:28:13

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

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

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

有没有一种方法可以单独改变特定单元格的颜色,而不影响行中的其他单元格?

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

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

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

不,这是不对的。它只会更改指定索引处单元格的文本颜色(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;

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

(例如,如果你在加载事件中设置了样式。它不会受到影响。但如果你像点击按钮或其他东西一样再次调用相同的函数,它会起作用)

解决方法:

在DatagridView_DataBindingComplete事件中设置样式。它可以很好地工作并更改颜色,您也可以

使用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();
   }

您可以使用

dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = Color.Blue;