Description:
How do I set the color or a row based on a value in a column?
Answer:
There are two solutions:
- Define a format condition;
- Handle the RowCellStyle event.
This article explains the second solution.
You should set the e.Appearance.BackColor parameter within the RowCellStyle event handler. A cell is defined by the e.RowHandle and e.Column parameters; the cell's value is passed to the e.CellValue parameter.
Our task is to change the style of the whole row. This means that the e.Column parameter should be ignored. A certain column's value can be obtained via the GetRowCellValue method.
C#private bool IsShipToUSCanada(GridView view, int row) {
try {
string val = Convert.ToString(view.GetRowCellValue(row, "ShipCountry"));
return (val == "US" || val == "Canada");
}
catch {
return false;
}
}
private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e) {
if(IsShipToUSCanada(gridView1, e.RowHandle)) {
e.Appearance.BackColor = Color.LightGray;
}
}
Visual BasicPrivate Function IsShipToUSCanada(ByVal view As GridView, ByVal row As Integer) As Boolean
Try
Dim val As String = Convert.ToString(view.GetRowCellValue(row, "ShipCountry"))
Return (val = "US" OrElse val = "Canada")
Catch
Return False
End Try
End Function
Private Sub gridView1_RowCellStyle(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs) Handles gridView1.RowCellStyle
If IsShipToUSCanada(gridView1, e.RowHandle) Then
e.Appearance.BackColor = Color.LightGray
End If
End Sub
If you need to change the style of a single cell (column) instead of a row, you will need to check the e.Column parameter: change e.Appearnace only if e.Column denotes the desired column.
See Also:
DevExpress WinForms Cheat Sheet - Appearances and Skins
Customizing Appearances of Individual Rows and Cells
How to customize the Look-And-Feel of my grid cells
Disabled Cell Behavior
Hi Alex
Thank you for solution.
Excellent
how do i fire gridView1_RowCellStyle event (i mean on my aspx page)
Hello,
This KB article is related to WinForms XtraGrid. I have created a separate How to change a row style based on a column value ticket about this task and forwarded it to our ASP.NET support team.
We will answer this ticket shortly.