windowsforms-115548-controls-and-libraries-data-grid-appearance-and-conditional-formatting.md
Tip
Each Appearance object has its own priority. Please see the following help topic for information on how to change the default priority of appearance settings: Application Appearance and Skin Colors.
The GridView.Appearance property gives access to property sections with appearance settings for Grid UI elements (even and odd rows, focused cells, column headers, buttons, grid lines, etc.).
Use the View’s Appearance.FocusedCell property to customize the focused cell’s appearance settings:
gridView1.Appearance.FocusedCell.BackColor = DXSkinColors.FillColors.Warning;
gridView1.Appearance.FocusedCell.ForeColor = DXSkinColors.ForeColors.WindowText;
gridView1.Appearance.FocusedCell.BackColor = DXSkinColors.FillColors.Warning
gridView1.Appearance.FocusedCell.ForeColor = DXSkinColors.ForeColors.WindowText
The following image shows the result:
Use the View’s Appearance.FocusedRow property to customize appearance settings of cells displayed in the focused row:
gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Green;
gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Green
gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White
Set the View’s OptionsSelection.EnableAppearanceFocusedCell property to false to turn off the focused cell’s appearance settings:
gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView1.OptionsSelection.EnableAppearanceFocusedCell = False
Use the View’s Appearance.SelectedRow property to customize the appearance of selected rows/cells (when multiple row/cell selection is enabled):
// Activate multiple cell selection.
gridView1.OptionsSelection.MultiSelect = true;
gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
// Customize background and foreground colors of selected rows.
gridView1.Appearance.SelectedRow.BackColor = DXSkinColors.FillColors.Success;
gridView1.Appearance.SelectedRow.ForeColor = DXSkinColors.ForeColors.WindowText;
' Activate multiple cell selection.
gridView1.OptionsSelection.MultiSelect = True
gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect
' Customize background and foreground colors of selected rows.
gridView1.Appearance.SelectedRow.BackColor = DXSkinColors.FillColors.Success
gridView1.Appearance.SelectedRow.ForeColor = DXSkinColors.ForeColors.WindowText
A grid column’s GridColumn.AppearanceCell property specifies appearance and text format settings for cells that belong to this column. These settings override global appearance settings.
Run Demo: Appearance of column cells
The following example centers values in cells of the Name column:
using DevExpress.Utils;
gridView1.Columns["Name"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
gridView1.Columns["Name"].AppearanceCell.Options.UseTextOptions = true;
Imports DevExpress.Utils
Private gridView1.Columns("Name").AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center
Private gridView1.Columns("Name").AppearanceCell.Options.UseTextOptions = True
To highlight the currently active editor, handle the ColumnView.ShownEditor event and use the BaseView.ActiveEditor property to access the focused cell’s editor.
gridView.ShownEditor += (s, e) => {
GridView view = s as GridView;
gridView.ActiveEditor.BackColor = Color.DodgerBlue;
};
AddHandler gridView.ShownEditor, Sub(s, e)
Dim view As GridView = TryCast(s, GridView)
gridView.ActiveEditor.BackColor = Color.DodgerBlue
End Sub
Run Demo: Change the Active Editor’s Background Color
The following example highlights cells if a user changed/edited their values. The example handles GridView.CellValueChanged and GridView.RowCellStyle events.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using DevExpress.LookAndFeel;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
namespace DXApplication14 {
public partial class Form1 : XtraForm {
Dictionary<string, ModifiedCellInfo> modifiedRows;
public Form1() {
InitializeComponent();
modifiedRows = new Dictionary<string, ModifiedCellInfo>();
gridControl1.DataSource = DataItem.GetSampleData();
gridView1.CellValueChanged += GridView1_CellValueChanged;
gridView1.RowCellStyle += GridView1_RowCellStyle;
}
void GridView1_RowCellStyle(object sender, RowCellStyleEventArgs e) {
GridView view = sender as GridView;
string rowId = GetCellIdentifier(view, e.RowHandle, e.Column.FieldName);
if (modifiedRows.ContainsKey(rowId) && modifiedRows[rowId].FieldName == e.Column.FieldName)
e.Appearance.BackColor = DXSkinColors.FillColors.Warning;
}
void GridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) {
GridView view = sender as GridView;
string rowId = GetCellIdentifier(view, e.RowHandle, e.Column.FieldName);
if (!modifiedRows.ContainsKey(rowId)) {
modifiedRows.Add(rowId, new ModifiedCellInfo() { FieldName = e.Column.FieldName, InitialCellValue = e.OldValue });
return;
}
if(modifiedRows.ContainsKey(rowId) && modifiedRows[rowId].InitialCellValue.Equals(e.Value))
modifiedRows.Remove(rowId);
}
string GetCellIdentifier(GridView view, int rowHandle, string fieldName) {
return view.GetRowCellValue(rowHandle, "ID").ToString() + fieldName;
}
}
public class DataItem {
public DataItem(string firstName, string lastName) {
ID = Guid.NewGuid();
FirstName = firstName;
LastName = lastName;
}
public static List<DataItem> GetSampleData() {
return new List<DataItem>() {
new DataItem("Bart", "Arnaz"),
new DataItem("Leah", "Simpson"),
new DataItem("Arnold", "Schwartz"),
new DataItem("William", "Zimmer"),
new DataItem("Samantha", "Piper")
};
}
[Display(Order = -1)]
public Guid ID { get; private set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class ModifiedCellInfo {
public string FieldName { get; set; }
public object InitialCellValue { get; set; }
}
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports DevExpress.LookAndFeel
Imports DevExpress.XtraEditors
Imports DevExpress.XtraGrid.Views.Grid
Namespace DXApplication14
Partial Public Class Form1
Inherits XtraForm
Private modifiedRows As Dictionary(Of String, ModifiedCellInfo)
Public Sub New()
InitializeComponent()
modifiedRows = New Dictionary(Of String, ModifiedCellInfo)()
gridControl1.DataSource = DataItem.GetSampleData()
AddHandler gridView1.CellValueChanged, AddressOf GridView1_CellValueChanged
AddHandler gridView1.RowCellStyle, AddressOf GridView1_RowCellStyle
End Sub
Private Sub GridView1_RowCellStyle(ByVal sender As Object, ByVal e As RowCellStyleEventArgs)
Dim view As GridView = TryCast(sender, GridView)
Dim rowId As String = GetCellIdentifier(view, e.RowHandle, e.Column.FieldName)
If modifiedRows.ContainsKey(rowId) AndAlso modifiedRows(rowId).FieldName = e.Column.FieldName Then
e.Appearance.BackColor = DXSkinColors.FillColors.Warning
End If
End Sub
Private Sub GridView1_CellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs)
Dim view As GridView = TryCast(sender, GridView)
Dim rowId As String = GetCellIdentifier(view, e.RowHandle, e.Column.FieldName)
If Not modifiedRows.ContainsKey(rowId) Then
modifiedRows.Add(rowId, New ModifiedCellInfo() With {
.FieldName = e.Column.FieldName,
.InitialCellValue = e.OldValue
})
Return
End If
If modifiedRows.ContainsKey(rowId) AndAlso modifiedRows(rowId).InitialCellValue.Equals(e.Value) Then
modifiedRows.Remove(rowId)
End If
End Sub
Private Function GetCellIdentifier(ByVal view As GridView, ByVal rowHandle As Integer, ByVal fieldName As String) As String
Return view.GetRowCellValue(rowHandle, "ID").ToString() & fieldName
End Function
End Class
Public Class DataItem
Public Sub New(ByVal firstName As String, ByVal lastName As String)
ID = Guid.NewGuid()
Me.FirstName = firstName
Me.LastName = lastName
End Sub
Public Shared Function GetSampleData() As List(Of DataItem)
Return New List(Of DataItem)() From {
New DataItem("Bart", "Arnaz"),
New DataItem("Leah", "Simpson"),
New DataItem("Arnold", "Schwartz"),
New DataItem("William", "Zimmer"),
New DataItem("Samantha", "Piper")
}
End Function
Private privateID As Guid
<Display(Order := -1)>
Public Property ID() As Guid
Get
Return privateID
End Get
Private Set(ByVal value As Guid)
privateID = value
End Set
End Property
Public Property FirstName() As String
Public Property LastName() As String
End Class
Friend Class ModifiedCellInfo
Public Property FieldName() As String
Public Property InitialCellValue() As Object
End Class
End Namespace
Conditional formatting allows you to customize cell appearance in Grid Views and Banded Grid Views based on cell values.
Run Demo: Conditional Formatting
Use Conditional Formatting to do the following:
Enable the view’s OptionsMenu.ShowConditionalFormattingItem option to display the Conditional Formatting item in the column menu. A user can right-click a column header and select Conditional Formatting in the menu to add, modify, or clear formatting rules.
The Manage Rules… menu item allows users to create custom rules. Enable the ColumnViewOptionsFilter.FilterEditorAllowCustomExpressions property to display the Expression Editor button in the New Formatting Rule dialog.
To create a rule, do the following:
Click New Rule….
Select Use a formula to determine which cells to format and edit the rule.
Click the Format button to customize appearance settings that should be applied to cells with matching values. Click OK to close the Format Cells dialog box.
Click OK to create and apply the rule.
Create a style format condition (GridFormatRule).
Create a rule (a FormatConditionRuleBase descendant), customize its settings, and assign it to the GridFormatRule.Rule property of the style format condition.
Add the style format condition to the view’s FormatRules collection.
Tip
Use the style format condition’s GridFormatRule.Enabled property to enable or disable the rule.
You can use the FormatRuleBase.Description property to specify a text description for the created format rule.
The following code example creates a style format condition that highlights cells in the “CreateDate” column for orders created before the current year:
using System;
using System.Data;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors;
namespace DXApplication9 {
public partial class Form1 : DevExpress.XtraEditors.XtraForm {
public Form1() {
InitializeComponent();
gridControl1.DataSource = InitDataTable();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e) {
// Creates and initializes the style format rule.
FormatConditionRuleDateOccuring dateRule = new FormatConditionRuleDateOccuring();
dateRule.Appearance.BackColor = System.Drawing.Color.LightGreen;
dateRule.DateType = FilterDateType.PriorThisYear;
// Creates and initializes the style format condition.
GridFormatRule formatRule = new GridFormatRule();
formatRule.Rule = dateRule;
formatRule.Column = gridView1.Columns["CreateDate"];
formatRule.ColumnApplyTo = gridView1.Columns["CreateDate"];
// Adds the style format condition to the view's FormatRules collections.
gridView1.FormatRules.Add(formatRule);
// This can also be done as follows:
// GridFormatRule formatRule = gridView1.FormatRules.AddDateOccurringRule(gridView1.Columns["CreateDate"], FilterDateType.PriorThisYear, new DevExpress.Utils.AppearanceDefault(){ BackColor = System.Drawing.Color.LightGreen});
}
DataTable InitDataTable() {
DataTable table = new DataTable("DataRecords");
table.Columns.AddRange(new DataColumn[] {
new DataColumn("ID", typeof(Guid)),
new DataColumn("CreateDate", typeof(DateTime)),
new DataColumn("CustomerName", typeof(string))
});
table.Rows.Add(new object[] { Guid.NewGuid(), new DateTime(2024, 1, 1, 9, 44, 12), "Silva" });
table.Rows.Add(new object[] { Guid.NewGuid(), new DateTime(2023, 12, 31, 11, 15, 18), "Mike" });
table.Rows.Add(new object[] { Guid.NewGuid(), new DateTime(2023, 12, 31, 10, 20, 10), "Nathan" });
return table;
}
}
}
Imports System
Imports System.Data
Imports DevExpress.XtraGrid
Imports DevExpress.XtraEditors
Namespace DXApplication9
Partial Public Class Form1
Inherits DevExpress.XtraEditors.XtraForm
Public Sub New()
InitializeComponent()
gridControl1.DataSource = InitDataTable()
AddHandler Load, AddressOf Form1_Load
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
' Creates and initializes the style format rule.
Dim dateRule As New FormatConditionRuleDateOccuring()
dateRule.Appearance.BackColor = System.Drawing.Color.LightGreen
dateRule.DateType = FilterDateType.PriorThisYear
' Creates and initializes the style format condition.
Dim formatRule As New GridFormatRule()
formatRule.Rule = dateRule
formatRule.Column = gridView1.Columns("CreateDate")
formatRule.ColumnApplyTo = gridView1.Columns("CreateDate")
' Adds the style format condition to the view's FormatRules collections.
gridView1.FormatRules.Add(formatRule)
' This can also be done as follows:
'Dim formatRule As GridFormatRule = gridView1.FormatRules.AddDateOccurringRule(gridView1.Columns("CreateDate"), FilterDateType.PriorThisYear, New DevExpress.Utils.AppearanceDefault() With {.BackColor = System.Drawing.Color.LightGreen})
End Sub
Private Function InitDataTable() As DataTable
Dim table As New DataTable("DataRecords")
table.Columns.AddRange(New DataColumn() {
New DataColumn("ID", GetType(Guid)),
New DataColumn("CreateDate", GetType(Date)),
New DataColumn("CustomerName", GetType(String))
})
table.Rows.Add(New Object() { Guid.NewGuid(), New Date(2024, 1, 1, 9, 44, 12), "Silva" })
table.Rows.Add(New Object() { Guid.NewGuid(), New Date(2023, 12, 31, 11, 15, 18), "Mike" })
table.Rows.Add(New Object() { Guid.NewGuid(), New Date(2023, 12, 31, 10, 20, 10), "Nathan" })
Return table
End Function
End Class
End Namespace
Select a rule to duplicate.
Click the Duplicate Rule dropdown and select the column to which you want to apply the duplicated rule.
The Data Grid compares cell values and fills these cells with solid colors chosen from a palette. Based on your selection, the palette gradually shifts through two or three threshold colors.
Cells are partially filled with the selected color. The fill percentage depends on how small or large the cell value is compared to other values in this column. You can also draw a vertical axis at the zero value. In this instance, data bars for positive and negative values are displayed in opposite directions and are painted with different colors.
Icon sets allow you to label each value range with a corresponding icon.
Selected font settings, and background and foreground colors are applied to cells with values that meet specific criteria (for example, the top 10 column values).
Some format condition rules support animation effects. The animation effect is played when a cell value changes. Use the FormatConditionRuleBase.AllowAnimation property to enable animation.
The following animation temporarily highlights a cell with an icon or color when a cell value changes:
Tip
To customize row appearances in other Views, handle customization events of these views: CustomCardStyle, ItemCustomize, CustomDrawItem.
Handle the GridView.RowCellStyle event to change cell appearance dynamically. For example, you can highlight specific cells in response to events. The following code snippet changes the background color and content alignment for the Name column’s cells based on the Boolean value of the Mark column.
gridView.RowCellStyle += (sender, e) => {
GridView view = sender as GridView;
bool _mark = (bool)view.GetRowCellValue(e.RowHandle, "Mark");
if(e.Column.FieldName == "Name") {
e.Appearance.BackColor = _mark ? Color.LightGreen : Color.LightSalmon;
e.Appearance.TextOptions.HAlignment = _mark ? HorzAlignment.Far : HorzAlignment.Near;
}
};
AddHandler gridView.RowCellStyle, Sub(sender, e)
Dim view As GridView = TryCast(sender, GridView)
Dim _mark As Boolean = CBool(view.GetRowCellValue(e.RowHandle, "Mark"))
If e.Column.FieldName = "Name" Then
e.Appearance.BackColor = If(_mark, Color.LightGreen, Color.LightSalmon)
e.Appearance.TextOptions.HAlignment = If(_mark, HorzAlignment.Far, HorzAlignment.Near)
End If
End Sub
You can also handle the GridView.RowStyle event to process and paint rows and group rows individually. For example, the following code snippet highlights focused rows.
Color foreColor = Color.Brown;
Color backColor = Color.LightGreen;
// Change the appearance settings of row cells dynamically.
gridView.RowStyle += (sender, e) => {
GridView view = sender as GridView;
//Change the foreground and background colors of selected rows.
if(view.IsRowSelected(e.RowHandle)) {
e.Appearance.ForeColor = foreColor;
e.Appearance.BackColor = backColor;
/* This property controls whether settings of the RowStyle event have a higher priority
than the appearances specified by the GridViewAppearances.EvenRow
and GridViewAppearances.OddRow properties. */
e.HighPriority = true;
}
};
Dim foreColor As Color = Color.Brown
Dim backColor As Color = Color.LightGreen
' Change the appearance settings of row cells dynamically.
AddHandler gridView.RowStyle, Sub(sender, e)
Dim view As GridView = TryCast(sender, GridView)
' Change the foreground and background colors of selected rows.
If view.IsRowSelected(e.RowHandle) Then
e.Appearance.ForeColor = foreColor
e.Appearance.BackColor = backColor
' This property controls whether settings of the RowStyle event have a higher priority
' than the appearances specified by the GridViewAppearances.EvenRow
' and GridViewAppearances.OddRow properties.
e.HighPriority = True
End If
End Sub
The GridView.GroupLevelStyle event allows you to paint group rows dynamically and apply unique appearance settings for each group level. In the following example, different group row levels have different appearance settings.
gridView.GroupLevelStyle += (s, e) => {
if(e.Level == 0) {
e.LevelAppearance.ForeColor = Color.WhiteSmoke;
e.LevelAppearance.BackColor = Color.Salmon;
} else {
e.LevelAppearance.ForeColor = Color.FromArgb(50, 50, 50);
e.LevelAppearance.BackColor = Color.LightSalmon;
}
};
AddHandler gridView.GroupLevelStyle, Sub(s, e)
If e.Level = 0 Then
e.LevelAppearance.ForeColor = Color.WhiteSmoke
e.LevelAppearance.BackColor = Color.Salmon
Else
e.LevelAppearance.ForeColor = Color.FromArgb(50, 50, 50)
e.LevelAppearance.BackColor = Color.LightSalmon
End If
End Sub
Tip
Use the RefreshRow method to force the view to redraw the specified row. The RefreshData() method redraws all rows.
Tip
You can also handle ~CustomDraw events to customize row and cell appearances dynamically: CustomDrawCell, CustomDrawGroupRow, CustomDrawGroupRowCell, CustomDrawFooterCell, etc. The following demo shows these events in action: Custom Painting Demos.
This example creates a helper class that handles the RowCellStyle event and makes it easy to specify a cell color.
Appearance settings of individual cells have lower priority than custom Column.AppearanceCell settings. If you allow a user to select individual cells (OptionsSelection.MultiSelectMode = CellSelect) with custom appearances, all cells (selected and unselected) look the same. To highlight selected cells, handle the GridView.RowCellStyle event.
private void GridView1_RowCellStyle(object sender, RowCellStyleEventArgs e) {
GridView view = sender as GridView;
if(view.IsCellSelected(e.RowHandle, e.Column)) {
e.Appearance.BackColor = view.PaintAppearance.SelectedRow.BackColor;
e.Appearance.ForeColor = view.PaintAppearance.SelectedRow.ForeColor;
}
}
Private Sub GridView1_RowCellStyle(ByVal sender As Object, ByVal e As RowCellStyleEventArgs)
Dim view As GridView = TryCast(sender, GridView)
If view.IsCellSelected(e.RowHandle, e.Column) Then
e.Appearance.BackColor = view.PaintAppearance.SelectedRow.BackColor
e.Appearance.ForeColor = view.PaintAppearance.SelectedRow.ForeColor
End If
End Sub
The GridView.PaintAppearance property allows you to obtain appearance settings used for GridView (for example, the background color of selected rows).
To prevent the focused row from being highlighted in the GridView or its descendant, disable the GridOptionsSelection.EnableAppearanceFocusedRow option. The GridOptionsSelection.EnableAppearanceFocusedCell property allows you to disable the focused cell’s highlight color.
The following example disables focused cell appearance settings and keeps the focused row appearance when the grid control loses focus:
private void Form1_Load(object sender, EventArgs e) {
gridView1.OptionsSelection.EnableAppearanceHideSelection = false;
gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
}
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
gridView1.OptionsSelection.EnableAppearanceHideSelection = False
gridView1.OptionsSelection.EnableAppearanceFocusedCell = False
End Sub
Disable the GridOptionsSelection.EnableAppearanceHideSelection option to prevent selected/focused rows from being highlighted in a specific manner when the grid control is not focused.
You can use the following techniques to display selected rows and cells without highlight effects:
Assign regular row appearance to the GridViewAppearances.SelectedRow property:
Handle the GridView.RowStyle, GridView.RowCellStyle, or GridView.CustomDrawCell event and modify selected row appearance:
You can disable cells in rows that meet a specific condition. Disabled cells are grayed out according to skin settings. Users cannot edit disabled cells.
Refer to the following topic for detailed information and examples: Disabled Cell Behavior.
Use the HeaderPanel property to access global settings that specify the appearance and text formatting of all column captions. To wrap column caption text, do the following:
HeaderPanel.TextOptions.WordWrap property to WordWrap.Wrap.HeaderPanel.Options.UseTextOptions property to true.To override global appearance settings for an individual column, use the column’s AppearanceHeader property.
The following example wraps the Name column’s caption text. Play the animation to see the result.
using DevExpress.Utils;
gridView1.Columns["Name"].AppearanceCell.TextOptions.WordWrap = WordWrap.Wrap;
gridView1.Columns["Name"].AppearanceCell.Options.UseTextOptions = true;
gridView1.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True;
Imports DevExpress.Utils
Private gridView1.Columns("Name").AppearanceCell.TextOptions.WordWrap = WordWrap.Wrap
Private gridView1.Columns("Name").AppearanceCell.Options.UseTextOptions = True
gridView1.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True
See Also