Conditional DataGridView Formatting
You can use the 'CellFormatting' event of the DataGridView. The DataGridViewCellFormattingEventArgs contains indexes of the row and the column of the current cell as it is being bound. I hope my code example makes some sense to you:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Compare the column to the column you want to format
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")
{
//get the IChessitem you are currently binding, using the index of the current row to access the datasource
IChessItem item = sourceList[e.RowIndex];
//check the condition
if (item == condition)
{
e.CellStyle.BackColor = Color.Green;
}
}
}
Conditional formatting of DataGridView cell data - Change color on negative
By creating the following CellFormatting addition, I am able to use Excel style conditional colour formatting in the cells format field. Setting the colour for negative/positive/zero values is supported.
Format string is expected to be in the following format (all colours optional) :
[colour]<format for +value> ; [colour]<format for -value> ; [colour]<format for zero value>
..a test DGV column with conditional formatting
c = New DataGridViewColumn
c.Name = "AmountOUT"
c.DataPropertyName = c.Name
c.HeaderText = "AmountOUT"
c.CellTemplate = New DataGridViewTextBoxCell
c.DefaultCellStyle.Format = "[Green]£0.00;[Red]-£0.00;[Blue]zero"
.Columns.Add(c)
..
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
'Split format string to positive / negative / zero components
Dim posnegzero As List(Of String)
posnegzero = e.CellStyle.Format.Split(CChar(";")).ToList
Dim coloursPNZ As New List(Of String)
Dim remainderformatPNZ As String = ""
For Each s As String In posnegzero
If s.Contains("[") And s.Contains("]") Then
'Extract [xxx] contents
coloursPNZ.Add(s.Substring(s.IndexOf("[") + 1, s.IndexOf("]") - s.IndexOf("[") - 1))
'Append rebuilt format excluding [xxx]
remainderformatPNZ &= s.Substring(0, s.IndexOf("[")) & s.Substring(s.IndexOf("]") + 1, s.Length - s.IndexOf("]") - 1) & ";"
Else
coloursPNZ.Add("")
remainderformatPNZ &= s & ";"
End If
Next
'Set format excluding any [xxx] components
e.CellStyle.Format = remainderformatPNZ
'Check for positive value
If Val(e.Value) > 0 And coloursPNZ.Count >= 1 Then
If coloursPNZ(0) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(0))
End If
End If
'Check for negative value
If Val(e.Value) < 0 And coloursPNZ.Count >= 2 Then
If coloursPNZ(1) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(1))
End If
End If
'Check for zero value
If Val(e.Value) = 0 And coloursPNZ.Count >= 3 Then
If coloursPNZ(2) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(2))
End If
End If
End Sub
How to change DataGridView cell color based on value of Combobox?
To change the Background color you must subscribe to the CellFormatting
event. Then add this code to the event handler:
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = sender as DataGridView;
if (dgv.Columns[e.ColumnIndex].Name.Equals("Gender"))
{
if (e.Value != null && e.Value.ToString().Trim() == "Male")
{
dgv.Rows[e.RowIndex].Cells["name"].Style.BackColor = Color.White;
}
else
{
dgv.Rows[e.RowIndex].Cells["name"].Style.BackColor = Color.DarkGray;
}
}
}
To cause a validation when a new value is selected in your DataGridViewComboBoxCell
,subscribe to the CurrentCellDirtyStateChanged
event and try this code in its handler:
private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = sender as DataGridView;
DataGridViewCell cell = dgv.CurrentCell;
if (cell is DataGridViewComboBoxCell)
{
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
dgv.EndEdit();
}
}
Formatting Cells in a data gridview based on a value (any cells)
Using the line dgvMatching.datasource = myds.table[0];
simply add the CellFormatting
event to the dgvMatching
DataGridView
. Like below:
private void dgvMatching_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.Value != null) {
if (e.Value.ToString().Equals("false"))
e.CellStyle.BackColor = Color.Red;
}
}
How can I color rows in datagridview with condition C#
You can use Datagridview's Cell_Formatting
event.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "bool_badge" && dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
// if the column is bool_badge and check null value for the extra row at dgv
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "0")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.ForestGreen;
}
}
}
Result will be,
Hope helps,
Changing datagridview cell color based on condition
You need to do this
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow Myrow in dataGridView1.Rows)
{ //Here 2 cell is target value and 1 cell is Volume
if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition
{
Myrow .DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow .DefaultCellStyle.BackColor = Color.Green;
}
}
}
Meanwhile also take a look at Cell Formatting
Datagridview row formatting based on data
Do you want to highlight all of the rows that meet the condition?
You can go through row by row to see which rows satisfy the condition each time the DTP value changes.
Then, for each cell in these rows, change DataGridViewCell.Style however you want to highlight the rows. For each cell that is in a row that doesn't satisfy the constraint, set DataGridViewCell.Style to the default.
How to implement conditional formatting in a GridView
Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in this link.
ie something like
<%# FormatDataValue(DataBinder.Eval(Container.DataItem,"ItemValue")) %>
Then in your codebehind, you can add a Protected Function
Protected Function FormatDataValue(val as object) As String
'custom enter code hereformatting goes here
End Function
Or you could do something in the OnRowCreated event of the gridview, like in this link
<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />
this function is conditional formatting based on whether or not the datavalue is null/is a double
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
Object ob = drv["ItemValue"];
if (!Convert.IsDBNull(ob) )
{
double dVal = 0f;
if (Double.TryParse(ob.ToString(), out dVal))
{
if (dVal > 3f)
{
TableCell cell = e.Row.Cells[1];
cell.CssClass = "heavyrow";
cell.BackColor = System.Drawing.Color.Orange;
}
}
}
}
}
Related Topics
System.Valuetype Understanding
Gracefully Handling Corrupted State Exceptions
Setting Dropdownlist Selecteditem Programmatically
Why Does Guid.Tobytearray() Order the Bytes the Way It Does
Outofmemoryexception When I Read 500Mb Filestream
Asynchronous File Download with Progress Bar
ASP.NET Button Onclick Event Not Firing
How to Convert String to Integer in C#
Why C# Won't Allow Field Initializer with Non-Static Fields
Entity Framework Ef.Functions.Like VS String.Contains
Get Table-Data from Table-Name in Linq Datacontext
Why Cannot I Cast My Com Object to the Interface It Implements in C#
How to Retain Callsite Information When Wrapping Nlog
Using Linq Except Not Working as I Thought
How to Drag and Drop a Button from One Panel to Another Panel