How to: Create a Custom Formatter to Substitute Boolean Values with Appropriate Strings
- 2 minutes to read
The following example demonstrates how to substitute Boolean values in the XtraGrid’s column with specific strings using a custom formatter. See the Custom Formatting topic for general information on creating custom formatters. Note that Boolean values can also be custom formatted via the grid’s event (ColumnView.CustomColumnDisplayText).
In this example a custom formatter is created. It contains two internal variables that specify the strings that correspond to the true and false values. These are initialized with values in the custom formatter’s constructor. The object’s Format method inspects the current value to be formatted and returns an appropriate string. See the code below.
class BooleanFormatter : IFormatProvider, ICustomFormatter {
string trueString, falseString;
public BooleanFormatter(string trueString, string falseString) {
this.trueString = trueString;
this.falseString = falseString;
}
public object GetFormat(System.Type type) {
return this;
}
public string Format(string formatString, object arg, IFormatProvider formatProvider) {
bool formatValue = Convert.ToBoolean(arg);
if (formatValue)
return trueString;
else
return falseString;
}
}
Consider the column shown in the image below. It is bound to a Boolean field containing values that specify whether or not a car has an automatic transmission.
This column can be made more informative by replacing the true and false values with the ‘Automatic‘ and ‘Manual‘ strings respectively . The code below shows how to assign the BooleanFormatter to this column.
The column’s in-place editor must be a text editor, otherwise values will not be formatted. To use a text editor for in-place editing a RepositoryItemTextEdit object is assigned to the column’s GridColumn.ColumnEdit property.
using DevExpress.Utils;
// ...
colTransmission.ColumnEdit = colTransmission.View.GridControl.RepositoryItems.Add("TextEdit");
colTransmission.Caption = "Transmission Kind";
colTransmission.DisplayFormat.FormatType = FormatType.Custom;
colTransmission.DisplayFormat.Format = new BooleanFormatter("Automatic", "Manual");
The image below displays the result.