Reputation: 29
Tried to found aswer on this question, but didn't found anything working for me. I need to change font color (bacground color etc.) of a single cell in my dataGridView based on different conditions.Fof example - value in another cell from the same row in this dataGridView. All solution that i found previously doesn't solve this problem for me.
Below is my suggestion for solving this problem.
Upvotes: -1
Views: 1850
Reputation: 1
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView dr = (DataRowView)e.Row.DataItem;
string temp = dr[3].ToString().Trim();
int sub = int.Parse(temp);
foreach (TableCell cell in e.Row.Cells)
{
if (sub > 0)
{
e.Row.Cells[3].BackColor = Color.Coral;
}
if (sub > 25)
{
e.Row.Cells[5].BackColor = Color.Coral;
}
}
}
}
if this doesn't help please elaborate more on the requirement.
Upvotes: 0
Reputation: 30512
Every DataGridView has a DefaultCellStyle
. Every DataGridViewColumn
of thie DataGridView may have a DefaultCellStyle
. If this is NULL, then the DefaultCellStyle
of the DataGridView is used. To see the actual cell style used by the column, use InheritedCellStyle
Similarly, every DataGridViewCell has a Style
. if it is null, it uses the InheritedCellStyle
of the column of the cell, so if this column has a null DefaultCellStyle,
the DefaultCellStyle
of the DataGridView
is used. The actual used Style of the DataGridViewCell is in property InheritedCellStyle
.
If you only want to change the cell style of a certain cell X, just set the DefaultCellStyle. You can take a Clone of the InheritedStyle and change the properties.
void SetCellBackColor(DataGridViewCell cell, Color color)
{
cell.Style = (DataGridViewCellStyle)(cell.InheritedStyle.Clone());
// or slightly more efficient:
if (cell.Style == null)
cell.Style = (DataGridViewCellStyle)(cell.InheritedStyle.Clone());
cell.Style.BackColor = color;
}
void SetCellBackColorToDefault(DataGridViewCell cell)
{
// set Style to null; the Column's InheritedStyle will be used
cell.Style = null;
}
Upvotes: 0
Reputation: 29
Here is my solution: You need to create event datagridView_cell_Formating:
And add a code similar to this:
private void datagridView_cell_Formating(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Target_column")
{
if ((e.Value != null) && (dataGridView1.Rows[e.RowIndex].Cells["Condition_cell"].Value.ToString() == "value"))
{
e.CellStyle.ForeColor = Color.Yellow;
}
else if ((e.Value != null))
{
e.CellStyle.ForeColor = Color.Red;
}
}
}
Hope this will help somebody.
Upvotes: 0