Format Cell Values

  • 6 minutes to read

This topic covers methods you can use to format cell values and substitute display values with custom ones.

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.

The cells' data can be provided at data source level. You can also generate HTML text dynamically using unbound (calculated) columns.

RepositoryItemHypertextLabel in grid.png

Example:

Hyper Text module in the XtraEditors MainDemo

Standard .NET Formatting 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

GridColumn.DisplayFormat

This is the most common approach to formatting values in display mode (when cell editing is inactive).

Repository Item (in-place editor) Level

RepositoryItem.DisplayFormat and RepositoryItem.EditFormat

This approach 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 to a specific pattern and formatting values in edit mode.

Customizing the DisplayFormat property at the repository item level is helpful in the following cases:

  • When you want to share value formatting settings between multiple columns or controls: Create a repository item, customize its settings and assign the item to target columns/controls. See Editors and Simple Controls to learn more.
  • When you want to use different formatting settings for different cells within a single column: Create and customize multiple repository items, and then assign these repository items to target cells by handling the Data Grid's GridView.CustomRowCellEdit or LayoutView.CustomRowCellEdit event.

The Formatting Values topic provides more information on the standard .NET formatting mechanism. You can find examples below.

Example 1 - Formatting 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-DisplayFormat-Standard.png

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, value formatting performed using the DisplayFormat property is not persisted when you switch to cell editing. To perform cell formatting in edit mode, use masks (see a section below).

Example 2 - Composite Format Pattern

The following example shows how to add custom text to value formatting:

GridColumn-DisplayFormat-Custom.png

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.UnboundType = DevExpress.Data.UnboundColumnType.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 formatting scenarios. See Formatting Values for more information and examples.

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.

ColumnEdit-Mask

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:

ColumnEdit-Mask-example

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;
    }
}

Providing Custom Display Text via 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 CurrencyType 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.

CD_Formatting_EuroDollar_Ex

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;
        }
    }
}
See Also