Skip to main content
A newer version of this page is available. .
.NET Framework 4.5.2+

How to: Bind an XPCollection to the DataGrid

  • 2 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;
    public DateTime OrderDate;
    [Association("Customer-Orders")]
    public Customer Customer;
}

public class Customer : XPObject {
    public string Name;
    public int Age;
    // 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>("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