Format Cell Values
- 8 minutes to read
This topic covers methods you can use to format cell values and substitute real cell values with custom values.
See also: WinForms Cheat Sheet - Display Values Different from Real Underlying Values.
Unbound Columns
If you need to replace a cell value (for instance, show nothing in cells that display zeroes) and cannot use lookup editors, hide a column and create a new unbound column instead. Then you can handle the CustomUnboundColumnData event to replace values.
// Hide the original column
gridView1.Columns["Price"].Visible = false;
// Create a column that replaces the hidden column
GridColumn customColPrice = new GridColumn();
customColPrice.FieldName = "CustomPrice";
customColPrice.UnboundDataType = typeof(string);
customColPrice.Caption = "Custom Price";
customColPrice.Visible = true;
gridView1.Columns.Add(customColPrice);
// Handle CustomUnboundColumnData
gridView1.CustomUnboundColumnData += GridView1_CustomUnboundColumnData;
// Copy non-zero values and show empty cells instead of zeroes
void GridView1_CustomUnboundColumnData(object sender, DCustomColumnDataEventArgs e) {
GridView view = sender as GridView;
if (e.Column == view.Columns["CustomPrice"]) {
decimal sourceValue = (decimal)view.GetRowCellValue(
view.GetRowHandle(e.ListSourceRowIndex), view.Columns["Price"]);
e.Value = sourceValue == 0 ? String.Empty : sourceValue.ToString();
}
}
Standard .NET Format Mechanism - Format Patterns and Custom Formatters
You can employ the standard .NET formatting mechanism to format numeric and date-time column values based on a standard or custom pattern, perform composite formatting (combining standard format specifiers with custom text), and implement custom formatting by creating a custom formatting object.
You can access the formatting functionality at two levels:
Level | Property | Description |
---|---|---|
Column Level | This is the most common technique to format values in display mode (when cell editing is inactive). | |
Repository Item (in-place editor) Level | This technique can be used to format cell values in display mode and when the editing operation is initiated. However, we recommend using masks instead of the EditFormat property to restrict end-user input. Changing the DisplayFormat property value at the repository item level is helpful in the following cases:
|
The Format Cell Values topic contains more information on the standard .NET format mechanism. You can find examples below.
Example 1 - Format Numeric and Date-Time Display Values
In the following example, the Data Grid contains two columns displaying numeric and date-time values. Values in the Model Price column are formatted as currency; values in the Sales Date column are displayed as a long date pattern.
GridColumn colModelPrice = gridView1.Columns["ModelPrice"];
colModelPrice.DisplayFormat.FormatType = Utils.FormatType.Numeric;
colModelPrice.DisplayFormat.FormatString = "c0";
GridColumn colSalesDate = gridView1.Columns["SalesDate"];
colSalesDate.DisplayFormat.FormatType = Utils.FormatType.DateTime;
colSalesDate.DisplayFormat.FormatString = "D";
As mentioned above, values formatted with the DisplayFormat property are not persisted when you switch to cell edit mode. To format cells in edit mode, use masks (see the section below).
Example 2 - Composite Format Pattern
The following example shows how to add custom text to value formatting:
gridControl1.ForceInitialize();
colUnitPrice.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
colUnitPrice.DisplayFormat.FormatString = "UP={0:n3}";
colQuantity.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
colQuantity.DisplayFormat.FormatString = "{0:d6}";
colDiscount.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
colDiscount.DisplayFormat.FormatString = "({0:P0})";
// Calculated Total column:
GridColumn columnTotal = new GridColumn();
columnTotal.Caption = "Total";
columnTotal.FieldName = "Total";
columnTotal.OptionsColumn.AllowEdit = false;
columnTotal.UnboundDataType = typeof(decimal);
columnTotal.UnboundExpression = "[UnitPrice]*[Quantity]*(1-[Discount])";
gridView1.Columns.Add(columnTotal);
columnTotal.VisibleIndex = gridView1.VisibleColumns.Count;
columnTotal.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
columnTotal.DisplayFormat.FormatString = "TTL={0:c2}";
Custom formatters allow you to implement complex format scenarios. See the following topic for more information and examples: Formatting Values.
Masks
Masks are helpful when you need to provide cell value input according to a particular pattern, but are only in effect when a cell is in edit mode, by default. However, you can activate the UseMaskAsDisplayFormat option to use masks to format cell values in display mode.
Note
Activating the UseMaskAsDisplayFormat option may reduce the Grid Control’s performance when it is bound to a large data source.
To use a masked input, first explicitly assign a text editor (RepositoryItemTextEdit) or its descendant to a target column with the GridColumn.ColumnEdit property. Then, initialize the mask settings from the RepositoryItemTextEdit.Mask property as required.
See Input Mask to learn more.
Example
The following example shows how to use a mask in the Phone grid column to allow only phone numbers:
private void Form1_Load(object sender, EventArgs e) {
List<MyRecord> list = new List<MyRecord>();
list.Add(new MyRecord(1, "(900)1231213"));
list.Add(new MyRecord(2, "(910)2001415"));
list.Add(new MyRecord(3, "(920)1008090"));
list.Add(new MyRecord(4, "(930)5005545"));
gridControl1.DataSource = list;
RepositoryItemTextEdit textEdit = new RepositoryItemTextEdit();
textEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
textEdit.Mask.EditMask = "(\\(\\d\\d\\d\\) )?\\d{1,3}-\\d\\d-\\d\\d";
textEdit.Mask.UseMaskAsDisplayFormat = true;
gridControl1.RepositoryItems.Add(textEdit);
gridView1.Columns["Phone"].ColumnEdit = textEdit;
}
public class MyRecord {
public int ID { get; set; }
public string Phone { get; set; }
public MyRecord(int id, string phone) {
this.ID = id;
this.Phone = phone;
}
}
Display Custom Text with an Event
The ColumnView.CustomColumnDisplayText event can be handled to display custom text in specific cells.
Example
The following example shows how to dynamically customize the cell’s display text by handling the ColumnView.CustomColumnDisplayText event.
The grid View in the example contains the Currency Type and Price columns. If the currency type is equal to 0, the price is displayed in dollars; if it is equal to 1, it is displayed in euros.
using DevExpress.XtraGrid.Views.Base;
using System.Globalization;
// The cultures used to format the values for the two different currencies.
CultureInfo ciUSA = new CultureInfo("en-US");
CultureInfo ciEUR = new CultureInfo("fr-FR", false);
private void gridView1_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e) {
ColumnView view = sender as ColumnView;
if (e.Column.FieldName == "Price" && e.ListSourceRowIndex != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
{
int currencyType = (int)view.GetListSourceRowCellValue(e.ListSourceRowIndex, "CurrencyType");
decimal price = Convert.ToDecimal(e.Value);
switch (currencyType)
{
case 0: e.DisplayText = string.Format(ciUSA, "{0:c}", price); break;
case 1: e.DisplayText = string.Format(ciEUR, "{0:c}", price); break;
}
}
}
Unbound Columns and HTML Text
You can format cell text using a simplified HTML syntax by embedding a RepositoryItemHypertextLabel in-place editor into a column. This feature allows you to:
- Change the font, size, and color of a cell’s text.
- Display images.
- Insert clickable hyperlinks.
Cell data can be supplied at the data source level. You can also use unbound (calculated) columns to generate HTML text dynamically.
Example
Hyper Text module in the XtraEditors MainDemo