Log In
Home
Support
Demos
Documentation
Blogs
Training
Webinars
[Expand]General Information
[Collapse]WinForms Controls
  Prerequisites
 [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
   [Expand]Getting Started
   [Collapse]Binding to Data
    [Expand]Server Mode
     Grid Control Binding Specifics
     Posting Data to a Connected Database
     Unbound Columns
     Binding to Entity Framework Models
     Binding via Data Source Configuration Wizard
     Fluent API Support
     Member Table: Data Binding
     Tutorial: ADO.NET Data
     Tutorial: Create and Manage Columns at Design Time
     Tutorial: Create and Manage Data in Code and Apply Data Annotation Attributes
     Tutorial: Entity Framework Data
     Tutorial: Unbound Columns
     Tutorial: Working with Columns in Code
   [Expand]Grid View
   [Expand]View Technology
   [Expand]Grouping
   [Expand]Sorting
   [Expand]Summaries
   [Expand]Data Editing
   [Expand]Filtering and Locating Rows
   [Expand]Focus and Selection Handling
   [Expand]Processing Rows
   [Expand]Formatting Cell Values
   [Expand]Master-Detail Relationships
   [Expand]Asynchronous Image Load
   [Expand]Export and Printing
   [Expand]Appearance and Conditional Formatting
   [Expand]Batch Modifications
   [Expand]Hit Information
   [Expand]Hints
   [Expand]Popup Menus
   [Expand]Saving and Restoring Layouts
   [Expand]Visual Elements
   [Expand]Design-Time Features
   [Expand]Examples
   [Expand]End-User Capabilities
    Included Components
  [Expand]Vertical Grid
  [Expand]Pivot Grid
  [Expand]Tree List
  [Expand]Chart Control
  [Expand]Diagrams
  [Expand]Gauges
  [Expand]Map Control
  [Expand]Scheduler
  [Expand]Spreadsheet
  [Expand]Rich Text Editor
  [Expand]Spell Checker
  [Expand]Form Layout Managers
  [Expand]Navigation Controls
  [Expand]Printing-Exporting
  [Expand]PDF Viewer
   Reporting
  [Expand]Snap
  [Expand]TreeMap Control
 [Expand]Common Features
  Get More Help
 [Expand]API Reference
[Expand]ASP.NET Controls and MVC Extensions
[Expand]ASP.NET Bootstrap Controls
[Expand]WPF Controls
[Expand]Xamarin Controls
[Expand]Windows 10 App Controls
[Expand]Document Server
[Expand]Reporting
[Expand]Report Server
[Expand]Dashboard
[Expand]eXpressApp Framework
[Expand]CodeRush
[Expand]Cross-Platform Core Libraries
[Expand]Tools and Utilities
 End-User Documentation

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

Show Me

A complete sample project is available in the DevExpress Code Examples database at http://www.devexpress.com/example=T162611.

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.
Important

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

How would you rate this topic?​​​​​​​