[英]Change forecolor of specific cell in DataGridView
我正在尝试更改datagridview中特定单元格的前景色。 我想给同一行中的不同单元格使用不同的颜色。
grid.Rows[row].Cells[col].Style.ForeColor = Color.Red
使用以上内容将更改所有“行”颜色,而不仅仅是我要更改的单元格。
有没有办法只更改特定单元格的颜色-不影响该行的其他单元格?
似乎我需要更改一些我不熟悉的Row属性。
如果您在加载默认数据(datagridview.Datasource = Table)之后立即应用样式或设置Row.DefaultStyle,则直到下次加载网格时,它才会受影响。
(即,如果您在加载事件中设置样式。它将不会受到影响。但是,如果再次调用相同的功能,例如单击按钮后,它将起作用)
解决此问题:
在DatagridView_DataBindingComplete事件中设置样式。 它将正常工作并更改颜色,您也可以
使用以上内容将更改所有行颜色,而不仅仅是我要更改的单元格
不,这是不正确的。 它将仅更改指定索引处单元格的文本颜色(前景色)。
您需要检查您是否未在代码的其他位置设置行的前色。
以下代码可以很好地更改背面和原色
//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;
使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.