.NET Framework 4.5.2+
.NET Framework 4.5.2+
.NET Standard 2.0+
A newer version of this page is available. Switch to the current version.

How to: Bind an XPCollection to the DataGrid

  • 3 minutes to read

The following example demonstrates how to bind a collection of Customer objects to the DataGrid control at runtime.

Object Structure

The Customer class represents a single customer. Each customer can have multiple orders. Orders are represented by the Order class. Orders can be associated with a specific customer by creating a relationship between the Orders property in the Customer object (the primary key) and the Customer property in the Orders object (the foreign key).

Please note that the property implementations in these first samples don't have all the code in their setters that we recommend . We have shortened the sample code for brevity and simplicity. If you follow our tutorials, you will see the recommended way of implementing property setters illustrated.

public class Order : XPObject {
    public string ProductName {
        get { return fProductName; }
        set { SetPropertyValue(nameof(ProductName), ref fProductName, value); }
    string fProductName;

    public DateTime OrderDate {
        get { return fOrderDate; }
        set { SetPropertyValue(nameof(OrderDate), ref fOrderDate, value); }
    DateTime fOrderDate;

    public Customer Customer {
        get { return fCustomer; }
        set { SetPropertyValue(nameof(Customer), ref fCustomer, value); }
    Customer fCustomer;


public class Customer : XPObject {
    public string Name {
        get { return fName; }
        set { SetPropertyValue(nameof(Name), ref fName, value); }
    string fName;

    public int Age {
        get { return fAge; }
        set { SetPropertyValue(nameof(Age), ref fAge, value); }
    int fAge;

    // When one object relates to other objects, 
    // the "many" end of the association must be defined by an XPCollection class.
    public XPCollection<Order> Orders { get { return GetCollection<Order>(nameof(Orders)); } }

Binding Collection to DataGrid

The DataGrid can be bound to a collection of persistent objects via the DataSource property:

DataGrid grid = new DataGrid();
grid.DataSource = new XPCollection<Customer>();

The image below shows the result.


See Also