Collaborating with XtraGrid - Additional Tips
Download VB and C# sources for this article
Introduction
This whitepaper will give you step by step instructions on how to use eXpress Persistent Objects in conjunction with the XtraGrid and augments our previous white paper dedicated to this same topic (see XPO.NET at Your Service. Collaborating with XtraGrid. General Information).
This paper assumes that you have the two following products installed:
XtraGrid 2.0
eXpress Persistent Objects 1.0
Implementing Editors in Your Grid
The most common way to ease the process of typing data into the grid is by using lookup controls (or similar implementations such as comboboxes or listboxes). Rather than type a new value, these controls let the user select a desired value from a list of available values as defined in the control itself. The list can be fixed or dynamically created to suit the specific state of the application. Suppose we want to display personal information for the simple business model shown below.
[C#]
public class TestPerson: XPObject { public string Gender; public string FullName; }
To visualize the TestPerson type persistent objects in the XtraGrid, you should follow the instructions outlined in the previous paper (see Xpo.Net At Your Service. Collaborating with XtraGrid. General Information). Add a new XPCollection, XpoXtraDataAdapter and XtraGrid controls onto your form or component. Adjust the XPCollection control properties as shown below, and then set the Collection property of the XpoXtraDataAdapter to reference xpCollection1.


Now select the xpoXtraDataAdapter1 from the list of available data sources in the DataSource property of the XtraGrid control as shown below. All other properties are set to default values and left unchanged. In order to manipulate records in the XtraGrid, make the record navigator visible in the grid at run time by setting the UseEmbeddedNavigator property of the XtraGrid to True.

Now we can open the XtraGrid designer and select the columns to be displayed in the grid by clicking Retrieve Fields button in the Column Designer.

We are ready to implement an editor for the Gender field. An editor controls the way the data is displayed and modified in XtraGrid. Let us examine two editor types to be implemented in your application, ComboBoxEdit and LookUpEdit.
Implementing a ComboBoxEdit
A new editor can be created by selecting its type from the types enlisted in the ColumnEdit property under the ‘New’ section.
To designate the ComboBoxEdit editor for the Gender field, select the corresponding column in the Columns list, open the Column properties tab and choose new ComboBoxEdit in the ColumnEdit property.

A new repository item named repositoryItemComboBox1 will be added to the grid. You can name the repository item descriptively by populating its properties in the properties list and assigning its Name property, for instance, ‘GenderComboBox’.

Here you can specify the set of valid values for the Gender field, for example Male, Female and Unknown. To do this, select the Items property for the GenderComboBox and then click the ellipsis (...) button to invoke the String Collection Editor. Now you can type the items comprising the list of available values for the Gender field.

Click the OK button to save the string collection items. The columns are now ready to be displayed in the grid.
Run your application and add a new record in a grid via the record navigator (click ‘plus’ button). In the added record, click Gender field to populate the list of available values. You can select one from the list. Note: it is possible to type a brand new string value (i.e: not previously declared in the Items property) into the field. To disable this feature, change the TextEditStyle property of the repositoryItemComboBox1 from Standard to DisableTextEditor.

You can make many additional adjustments to the grid appearance through XtraGrid settings, for more information on this see the XtraGrid documentation.
In this example we maintained the control of the available values list through XtraGrid editor settings and designated the type of the Gender field as String. Though, we can also control the list of available values in the code. To do this, we shall define an enumeration to specify the values for the field as well as a wrapper control which will allow us to adjust the grid properties at design time. This time we select the LookUpEdit as an editor for the field.
LookUpEdit Implementation
First, let us define a Gender enumeration, assign its values, and then, create a new class similar to the TestPerson class with Gender property of the enumeration type we created.
[C#]
public enum Gender { Female, Male, Unknown } public class TestPerson2: XPObject { public Gender Gender = Gender.Male; public string FullName; }
To display the TestPerson2 object in a grid, select it in the ObjectClassInfo property of the xpCollection1.
Use the following code to define EnumList control in the same namespace where your application classes reside. The components inherited from the EnumList class can be displayed at design time and be available as data sources for data-aware controls, such as XtraGrid.
[C#]
public class EnumList: System.ComponentModel.Component, IListSource { System.ComponentModel.Container components = null; Type type = null; EnumWrapper[] enums = null;
class EnumWrapper { Enum _enum = null; public EnumWrapper(Enum _enum) { this._enum = _enum; } public Enum Enum { get { return _enum; } } public string String { get { return _enum.ToString(); } } } public Type EnumType { get { return type; } set { if(!value.IsEnum) throw new ArgumentException("The provided type is not an enumeration!", "EnumType"); FieldInfo[] fields = value.GetFields(BindingFlags.Public | BindingFlags.Static); int size = fields.Length; enums = new EnumWrapper[size]; for(int i = 0; i < size; i++) { Enum e = (Enum)fields[i].GetValue(null); enums[i] = new EnumWrapper(e); } type = value; } }
public EnumList(System.ComponentModel.IContainer container) { container.Add(this); InitializeComponent(); } public EnumList() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } public bool ContainsListCollection { get { return false; } } public IList GetList() { return enums; } private void InitializeComponent() { components = new System.ComponentModel.Container(); } }
We will skip details on how to create an EnumList component from the Toolbox as this is the standard way to accomplish the task. An alternate way is by placing the declaration of the Gender enumeration list to the form’s private members declaration area
[C#]
public class Form3: System.Windows.Forms.Form { ... private EnumList genderEnumList; ...
and subsequent addition the enumeration list control to the form
[C#]
private void InitializeComponent() { ... this.genderEnumList = new XtraGridDataTableAsDataSource.EnumList(this.components); ...
Finally, we have to initialize the control before the grid control initialization inside the form’s InitializeComponent() method
[C#]
this.genderEnumList.EnumType = typeof(Gender);
The form now looks like the following.

Now we can specify an editor to display the enumeration elements in the grid. In the XtraGrid Column Designer, select the colGender column and set a new LookUpEdit in the ColumnEdit property. A new repository item named repositoryItemLookUpEdit1 will be added to the grid. Navigate to the Repository Editor and select the repositoryItemLookUpEdit1 to adjust its properties. Name it by assigning the corresponding property, for example, ‘GenderLookUp’. To define the data displayed and the value stored in the grid, set the DisplayMember property and the ValueMember property accordingly. The data to be displayed is available through the String property of the genderEnumList, whereas the value is represented by the Enum property.
Now we can define the data to be displayed in a LookUpEdit, i.e. GenderLookUp. First, select the genderEnumList from the list of available data sources in the DataSource property of the GenderLookUp editor. Second, specify the columns to be visible in the lookup. Select Columns property in the properties list then click the ellipsis (...) button to invoke the LookUpColumnInfo Collection Editor. In the opened window, click Populate Columns button to retrieve all columns from the data source provided.

We have two columns fetched to the Members list – Enum and String. Remove the Enum column from the Members list as we want only one column, named String, to be visible at run time. To modify a caption for the String column, that is equal to the column name by default, set a more descriptive value, for example, ‘Gender’, to the Caption property.

Click the OK button to save the Columns collection property.
Now we are ready to see results.

Now we’ll go back to the business model introduced in the previous paper. You learned how to display orders information for the customers. Suppose you want to display all orders and customers linked to the specified order item. With XPO you virtually need to do nothing to specify additional information about the ‘One’ end of the ‘Customer-Orders’ relation. All data can be automatically acquired from the association.
Generally, the task is almost the same as for the original example. We provide orders information for the grid by adding a new XPCollection and XpoXtraDataAdapter pair. To do this, drag an XPCollection object from the Developer Express tab of the Toolbox onto your form or component. Select Order object in the ObjectClassInfo property list. Now let us specify the data sufficient for displaying order information. Date and Amount fields fit the case, so we’ll adjust DisplayableProperties correspondingly. Finally, name this collection of orders, say ‘xpCollectionOrders’.

Now let us create a new XpoXtraDataAdapter and link it to the xpCollectionOrders to adopt its data for the XtraGrid.

Now you can run the application and you should see the following grid.

Note that we have not specified the customer information to be displayed in the grid. Obviously, there is only one customer associated with the order item. Therefore, we can display customer-related information, such as full name in the same row as the order item. To do that, let us add the Customer! property to the DisplayableProperties list. This property can be used in the editor control to reference the Customer object. Now you can define columns and adjust its properties in the Column Designer to display information related to the order and customer. Click Retrieve Fields to get the fields out of the XPCollection.

A new column named gridColumn3 is responsible for displaying Customer information. In order to modify the customer associated with an order item, specify an editor control for the column. Since it is more comfortable to select a customer from the list of available customer records rather than type it, a LookUpEdit will best fit this task. Select a new LookUpEdit as a ColumnEdit for the gridColumn3. This action adds a new repository item to the list of repository items in the Repository Editor. Let us adjust item’s properties as follows. Set DataSource property to xpoXtraDataAdapter1 (this one is used to display customers). Then define a column being displayed by the lookup in the Columns collection property. You can populate the list of columns using LookUpColumnInfo Collection Editor. The only columns we need here are FullName and Telephone.

The data to be displayed comprised by the FullName property, whereas the value will be represented by This object reference.
That’s it! Now the customer associated with the order item can be displayed and modified right in a grid.

Using the DataTable as a DataSource for a Column Editor
You learned how to provide the data to display in a grid by means of the XtraGrid column editor items and by enumeration values declared in the code. Another source of data for a column editor might well be a data table. For example, we want to display enumeration values with descriptions stored in a data table. This table is a reference book for the enumeration you defined in the code. To illustrate this approach, let us create a new class, an extended version of the TestPerson2 class with the Maturity property of the enumeration type as in the following code example.
[C#]
public enum Maturity { Adult, Child, Older, Teenager } public class TestPerson3: XPObject { public Gender Gender = Gender.Male; public Maturity Maturity = Maturity.Adult; public string FullName; }
To display the TestPerson3 objects in a grid, do not forget to select it in the ObjectClassInfo property of the xpCollection1.
Now let us define the data table. Create an instance of a new, untyped dataset in your form. To do this, from the Data tab of the Toolbox, drag a DataSet object onto your form or component. In the ‘Add Dataset’ window, select ‘Untyped dataset’ option and click OK button. In the properties list of the dataset, add new table named ‘Enumeration’ to the Tables collection, then add two columns Enum and Description to represent the enumeration values and their descriptions as shown below.


All other properties of the columns, the table and the dataset are set to the default values and left unchanged.
Since we have changed the data source for the XtraGrid, we must add a column for the Maturity field to the Columns list. Run XtraGrid designer and navigate to Column Designer. Click Add button and set Name, Caption and FieldName properties of the new column as shown below.

Now we can specify an editor to display the data from the data table in the grid as we did for the Gender field. Select the colMaturity column and set a new LookUpEdit in the ColumnEdit property. A new repository item will be added to the grid. In the Repository Editor, set the item’s name, for example, ‘MaturityLookUp’ and then, select the data table we created as DataSource for the editor. DisplayMember property and ValueMember property we set to Description field and Enum field correspondingly. Now we specify the columns to be visible in the lookup. Set the Columns property as we did before. In the LookUpColumnInfo Collection Editor populate the columns from the data table we provided. Enum and Description fields will be added to the Columns collection.
Let us initialize the data table in the form’s constructor.
[C#]
public Form4() { ... InitializeComponent(); ...
dataTable1.Columns["Enum"].DataType = typeof(Enum); Type t = typeof(Maturity); Enum _enum; foreach(FieldInfo field in t.GetFields(BindingFlags.Public | BindingFlags.Static)) { _enum = (Enum)field.GetValue(null); string description = _enum.ToString(); dataTable1.Rows.Add(new object[] {_enum, description} ); } ... }
We defined the description as a string portion of the enumeration; you may want to set it to be quite different and more descriptive, though.
The resulting grid has the following view.

This is exactly what we need.
Summary
These papers have presented the synergies of two DevExpress products working together to improve your developer experience. The techniques shown provide a simple way of supplying the developer with tips of data visualization in the XtraGrid. The flexibility of the XtraGrid empowered by the simplicity of the data representation approach of the XPO allows the design of your application to have an elegant simplicity that makes design a breeze and maintenance a dream.
Guaranteed!
Download VB and C# sources for this article To learn more about XPO, please write to us at: info@devexpress.com.
To order your copy, visit our online order page.
|