[Expand]General Information
[Collapse]WinForms Controls
 [Expand]What's Installed
 [Expand]Build an Application
 [Collapse]Controls and Libraries
  [Expand]Forms and User Controls
  [Expand]Messages, Notifications, and Dialogs
  [Expand]Editors and Simple Controls
  [Expand]Ribbon, Bars and Menu
  [Expand]Application UI Manager
  [Expand]Docking Library
  [Collapse]Data Grid
   [Collapse]Get Started With Data Grid and Views
     [Expand]Appearance and Conditional Formatting
     [Expand]Data Editing
     [Expand]Hit Information
     [Collapse]Data Binding and Working with Columns
       Tutorial: ADO.NET Data
       Tutorial: Working with Columns in Code
       Tutorial: Unbound Columns
       Tutorial: Create and Manage Columns at Design Time
       Tutorial: Entity Framework Data
       Tutorial: Create and Manage Data in Code and Apply Data Annotation Attributes
       Tutorial: Large Data Sources and Instant Feedback with Server Mode
     [Expand]Grid View - Columns, Rows and Cells
     [Expand]Banded Views
     [Expand]WinExplorer View
     [Expand]Tile View
     [Expand]Filter and Search
     [Expand]Split Presentation
     [Expand]Row Preview Sections
   [Expand]Data Binding
    Unbound Columns
   [Expand]Data Editing and Validation
   [Expand]Filter and Search
   [Expand]Focus and Selection Handling
    Format Cell Values
   [Expand]Master-Detail Relationships
   [Expand]Asynchronous Image Load
   [Expand]Export and Printing
   [Expand]Appearance and Conditional Formatting
    Split Presentation
    Row Preview Sections
   [Expand]Batch Modifications
    Hit Information
    Popup Menus
   [Expand]Save and Restore Layout
   [Expand]Visual Elements
   [Expand]Design-Time Features
   [Expand]End-User Capabilities
    Included Components
  [Expand]Vertical Grid
  [Expand]Property Grid
  [Expand]Pivot Grid
  [Expand]Tree List
  [Expand]Chart Control
  [Expand]Map Control
  [Expand]Rich Text Editor
  [Expand]Spell Checker
  [Expand]Form Layout Managers
  [Expand]Navigation Controls
  [Expand]PDF Viewer
  [Expand]TreeMap Control
  [Expand]Sunburst Control
 [Expand]Common Features
  Get More Help
 [Expand]API Reference
[Expand]ASP.NET Controls and MVC Extensions
[Expand]ASP.NET Bootstrap Controls
[Expand]ASP.NET Core Bootstrap Controls
[Expand]WPF Controls
[Expand]Xamarin Controls
[Expand]Windows 10 App Controls
[Expand]Office File API
[Expand]Report and Dashboard Server
[Expand]eXpressApp Framework
[Expand]eXpress Persistent Objects
[Expand]CodeRush Classic
[Expand]Cross-Platform Core Libraries
[Expand]Tools and Utilities
 End-User Documentation
View this topic on docs.devexpress.com (Learn more)

Tutorial: Create and Manage Data in Code and Apply Data Annotation Attributes

This walkthrough is a transcript of the Create and Manage Data in Code and Apply Data Annotation Attributes video available on the DevExpress YouTube Channel.

In this tutorial, you will learn how to create a data source for your grid control in code. You will also see how to apply data attributes to make the grid apply appropriate editing modes, cell editors and input validation rules.

Expanded Creating a Simple Data Source Using DevExpress Project Wizard

Start by creating a project with the DevExpress Project Wizard available at the DevExpress Templates collection as you create a new solution.

Launch the app to see that there's sample data displayed by the grid.

Switch to code to locate the source of this data. There's code automatically generated by the wizard, including the InitGrid method call in the form constructor. This method populates a BindingList with 5 instances of the Person class. The BindingList object is then assigned to the gird control's GridControl.DataSource property.

This is how you can create data in code in the simplest case. Define an object representing a record, then create a collection of such objects and assign the collection to the grid's GridControl.DataSource property.

Expanded Creating More Complex Data Source

Now see a few more examples of creating data in code and then binding it to the grid.

You can define your custom classes that would serve as data records. The sample code file in this tutorial contains definitions of 3 classes: CompanyPublicInfo, CompanyPrivateInfo and Product, each including its own properties that will serve as data fields.

The GridSampleDataList class defined later in this file provides 3 methods: GetCompanyPrivateInfo, GetCompanyPublicInfo and GetProductSample. Each of these methods returns a BindingList populated with objects of corresponding classes.

Now create the UI allowing application users to switch between these three data sources. Return to the main form design where you can see the editor added to the Ribbon Control. The dropdown list will have three items corresponding to data source types defined earlier.

Now handle the BarEditItem.EditValueChanged event to assign different BindingList objects to the grid's GridControl.DataSource depending on the currently selected dropdown list item.

To make sure that grid columns are re-created based on the currently available data fields, handle the GridControl.DataSourceChanged event that fires each time the grid receives a new data source. In the event handler, simply call the ColumnView.PopulateColumns method that does exactly what is needed.

Run the application to see how this works. The application still starts with auto-generated sample data. If you select an item from the dropdown list in the Ribbon, the grid will display data from the corresponding data source.

Expanded Applying Data Annotation Attributes

Notice that all grid columns are displayed with their default editors and have default formatting applied. For instance, the Product Info data contains multi-line text that cannot be viewed entirely since the default grid cell editor allows only single-line text. Company Public Info data includes URLs and e-mails that are displayed as simple text strings, as well as phone numbers that should ideally use a phone mask format. Finally, the Private Company Info displays passwords that should not be immediately visible.

One way to change this is by accessing column objects and updating their settings. But that would mean that you should do this every time you bind your data source to a data-aware control. Another way to do this is by using Data Annotation Attributes provided by Microsoft and supported by most DevExpress data-aware controls. To be able to use these attributes, make sure your application references the System.ComponentModel.DataAnnotations namespace.

There are two ways to use these attributes. The first and simplest method is to define required attributes before each data field. This is what is done for the Product class. Some attributes indicate data types so that an appropriate cell editor can be assigned. The ReadOnly attribute allows you to disable data editing for a specific field. You can also apply data input validation rules, as it is done by the Range attribute.

Launch the app and switch to the Product Info data to see how it looks now. The multiline text uses the MemoEdit cell editor that allows us to view the text entirely, and the Currency column allows only data in the specified range.

This approach is most useful when you have unique data fields that are not used in multiple classes. Another way to accomplish the same task is by using the MetadataType class attribute. Using this approach, you can define a data field attribute once and then use the definition for multiple classes. It can also improve code readability, since data attributes don't have to precede every property definition.

Both Private and Public Company Info classes will use metadata defined by the CompanyProductMetadata class.

Run the application to see the result. Switch to the Public Company Info data source to see that URLs are now displayed as actual hyperlinks and phone numbers use masked input.

Expanded Complete Code

The solution in this example includes a DataSource file that has three classes that provide grid data - CompanyPublicInfo, CompanyPrivateInfo and Product. Properties for all three of them derive Data Annotation Attributes from the CompanyProductMetadata class by using the MetadataType attribute. End-users can use the editor at the top of the form to call one of the Get... methods that will populate the grid with sample data.


To work with Data Annotation Attributes, you need to reference the System.ComponentModel.DataAnnotations library in your solution.

Is this topic helpful?​​​​​​​