Reputation: 61
I am trying to change the forecolor of a specific cell in datagridview. I want to give different colors to different cells in the same row.
grid.Rows[row].Cells[col].Style.ForeColor = Color.Red
Using the above will change all the Row color and not just the cell I want to change.
Is there a way to change color of specific cell solely - not affecting other cells of the row?
It seems like I need to change some Row property that I am not familiar with.
Upvotes: 4
Views: 7610
Reputation: 1201
If you apply the Style or set Row.DefaultStyle immediately after loading the default data(datagridview.Datasource=Table), it will not affect until you load grid next time.
(ie if you set style in load event.It wont get affected.But if you call the same function again like after clicking button or something it will work)
Work around for this :
Set the style in DatagridView_DataBindingComplete event. It will work fine and change the color you can also
Upvotes: 1
Reputation: 650
Use the CellFormatting event:
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; }
}
in if you can write your condition to find specific cell.
or try this one.
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();
}
Upvotes: 0
Reputation: 32719
Using the above will change all the Row color and not just the cell I want to change
No, this is not correct. It will only change the text color (Forecolor) of the cell at the specified index.
You need to check that you are not setting the forecolor of row somewhere else in your code.
following code works fine for Changing the back and 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;
Upvotes: 3
Reputation: 7601
you can use
dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = Color.Blue;
Upvotes: -1