HOME PAGE | DOWNLOAD | TUTORIALS | XtraReports
Devexpress

Thursday, July 19, 2012

WinForms Grid - How to Implement a Custom Formatter to Replace Boolean Values with Strings

You can use custom formatters to change the way data is formatted and represented in the XtraGrid. For example, in this video we will demonstrate how to create a custom formatter to substitute Boolean Values with True and False Strings.

So let’s get started…

1.       Starting from a new WinForms application, I drop an XtraGrid control onto the form and dock it to its parent.

2.       I run the Grid’s Designer and switch to the Columns page.

3.       Here, I will create three unbound columns.

4.       I’ll call them “Make”, “Model”, and “Automatic”.

5.       I close the designer and return to Visual Studio.

6.       I switch to code view.

7.       In “Form1.cs”, I add a small class to store my data.

8.       For the purpose of this example, I’m going to use a simple list as my data source.

9.       In the form’s constructor, I create a field to hold the list of data I’m using.

10.   Next, I create some test data and bind it to the grid.

11.   You’ll notice that these entries have a Boolean value.

12.   I run the application.

13.   You can see that the grid is populated with my test data. The “Automatic” column which contains Boolean values is displayed as checkboxes.

14.   My goal is to substitute the checkboxes with meaningful phrases.

15.   I close the application and return to Visual Studio.

16.   In code view, I add the following class to the “Form1.cs” file.

17.   Here, I’ve created a custom formatter. It contains two internal variables that specify the strings corresponding to the true and false values. These variables are initialized in the custom formatter's constructor.

18.   The object's Format method inspects the current value to be formatted and returns an appropriate string.

19.   Now, I’m going to rename the “Automatic” column and substitute its Boolean values with appropriate strings.

20.   I switch to design view and create a handler for the Form’s Load Event.

21.   Back in code view, I add the following code to the event handler.

22.   This will rename the “Automatic” column to “Transmission Kind” as well as replace “true” with the string “Automatic” and “false” with the string “Manual”.

23.   And I’m done!

24.   I run the application to see the results.

25.   You can now see that the “Automatic” column is now called “Transmission Kind” and its values have been changed to the appropriate string.

As you saw in this video, implementing a custom formatter means creating a method that will return formatted strings by taking the original value and the format string as its parameters. Therefore, it is up to you to produce the formatting logic, giving you an infinite number of possibilities.

No comments:

Post a Comment