Back to Devexpress

How to: Format Display Text in Grid's Cells Depending on Values in Other Cells

windowsforms-3048-controls-and-libraries-data-grid-examples-formatting-how-to-format-display-text-in-grids-cells-depending-on-values-in-other-cells.md

latest2.7 KB
Original Source

How to: Format Display Text in Grid's Cells Depending on Values in Other Cells

  • Aug 01, 2019
  • 2 minutes to read

The following code snippet handles the CustomColumnDisplayText event to format prices based on a currency type column.

The currency type column contains only 0 and 1 values. If the currency type equals 0 , the price is displayed in US dollars. If the currency type equals 1 , the price is displayed in euros.

csharp
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid;
using System.Globalization;

// Culture settings for currency formatting
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;

    // Process only valid data rows and the Price column.
    if (e.Column.FieldName != "Price" || e.ListSourceRowIndex == GridControl.InvalidRowHandle)
        return;

    int currencyType = (int)view.GetListSourceRowCellValue(e.ListSourceRowIndex, "CurrencyType");

    decimal price = Convert.ToDecimal(e.Value);

    // Select format based on currency type.
    e.DisplayText = currencyType == 0
        ? string.Format(ciUSA, "{0:c}", price)
        : string.Format(ciEUR, "{0:c}", price);
}
vb
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid
Imports System.Globalization

' Culture settings for currency formatting
Private ciUSA As New CultureInfo("en-US")
Private ciEUR As New CultureInfo("fr-FR", False)

Private Sub gridView1_CustomColumnDisplayText(
    sender As Object,
    e As CustomColumnDisplayTextEventArgs)

    Dim view As ColumnView = TryCast(sender, ColumnView)

    ' Process only valid data rows and the Price column.
    If e.Column.FieldName <> "Price" _
        OrElse e.ListSourceRowIndex = GridControl.InvalidRowHandle Then
        Return
    End If

    ' Read the currency type from the current row.
    Dim currencyType As Integer = CInt(
        view.GetListSourceRowCellValue(e.ListSourceRowIndex, "CurrencyType"))

    ' Convert the original value to Decimal.
    Dim price As Decimal = Convert.ToDecimal(e.Value)

    ' Select the display format based on the currency type.
    If currencyType = 0 Then
        e.DisplayText = String.Format(ciUSA, "{0:c}", price)
    Else
        e.DisplayText = String.Format(ciEUR, "{0:c}", price)
    End If
End Sub