Skip to main content
.NET 6.0+

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

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;

    [Association("Customer-Orders")]
    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.
    [Association("Customer-Orders")]
    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();
this.Controls.Add(grid);
grid.DataSource = new XPCollection<Customer>();

The image below shows the result.

DataGridBinding

See Also