Skip to main content

Lesson 1 - Bind a Grid to Data

  • 5 minutes to read

Important

This documentation topic describes legacy technology. We no longer develop new functionality for the GridControl and suggest that you use the new DataGridView control instead.

This document describes how to bind a grid to data created at runtime. To learn more about this procedure, you can also watch a video below.

Create a Solution with a Grid

  1. Create a new Xamarin.Forms cross-platform solution (HelloGrid) in Xamarin Studio and include the DevExpress Grid component.
  2. Add a new content page to the PCL project. To do this, right-click the project, and select Add | New File…. In the invoked dialog, switch to the Forms section and select Forms ContentPage Xaml. Enter the name MainPage.

    Grid_GettingStarted_AddNewFile

  3. Open the App.cs file and modify the GetMainPage method to set the newly created page as the start page of the application.

    public class App : Application {
        public App() {
            this.MainPage = GetMainPage();
        }
        public static Page GetMainPage () {
            return new MainPage ();
        }
    }
    
  4. Add a grid to the page at design time (by using the XAML markup in the MainPage.xaml file).

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
                 x:Class="HelloGrid.MainPage"
                 xmlns:dxGrid="clr-namespace:DevExpress.Mobile.DataGrid;assembly=DevExpress.Mobile.Grid.v18.2">
        <dxGrid:GridControl x:Name="grid">
        </dxGrid:GridControl>
    </ContentPage>
    

Prepare a Data Source

The GridControl does not support the unbound mode in which records would be added directly to a grid. Instead, records must be added to a bound data source and then appear in the grid. In this example, the grid will be bound to data created at runtime.

Declare the Order class encapsulating an individual data record. Its public properties (Date, Shipped, Product and Quantity) will be data source fields.

public class Order : ModelObject {
    DateTime date;
    bool shipped;
    Product product;
    int quantity;

    public Order() {
        this.date = DateTime.Today;
        this.shipped = false;
        this.product = new Product ("", 0);
        this.Quantity = 0;
    }

    public Order(DateTime date, bool shipped, Product product, int quantity) {
        this.date = date;
        this.shipped = shipped;
        this.product = product;
        this.quantity = quantity;
    }

    public DateTime Date {
        get { return date; }
        set { if (date != value) {
                date = value;
                RaisePropertyChanged("Date");}}
    }

    public bool Shipped {
        get { return shipped; }
        set { if(shipped != value) {
                shipped = value;
                RaisePropertyChanged("Shipped");}}
    }

    public Product Product {
        get { return product; }
        set { if (product != value) {
                product = value; 
                RaisePropertyChanged ("Product");}}
    }

    public int Quantity {
        get { return quantity; }
        set { if (quantity != value) {
                quantity = value; 
                RaisePropertyChanged ("Quantity");}}
    }
}

public class Product : ModelObject {
    string name;
    int unitPrice;

    public Product(string name, int unitPrice) {
        this.name = name;
        this.unitPrice = unitPrice;
    }

    public string Name {
        get { return name; }
        set { name = value; }
    }

    public int UnitPrice{
        get { return unitPrice; }
        set { unitPrice = value; }
    }
}

public class ModelObject : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string name) {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

A collection of Order objects will be the data source for the grid. This collection is returned by the Orders property of the TestOrdersRepository class.

using DevExpress.Mobile.Core.Containers;
...

public abstract class OrdersRepository {
    readonly BindingList<Order> orders;

    public OrdersRepository() {
        this.orders = new BindingList<Order>();
    }

    public BindingList<Order> Orders {
        get { return orders; }
    }
}

public class TestOrdersRepository : OrdersRepository {

    const int orderCount = 100;
    readonly List<Product> products;
    readonly Random random;

    public TestOrdersRepository() : base() {
        this.random = new Random((int)DateTime.Now.Ticks);
        this.products = new List<Product>();

        GenerateProducts();

        for (int i = 0; i < orderCount; i++)
            Orders.Add(GenerateOrder(i));
    }

    Order GenerateOrder(int number) {
        Order order = new Order(new DateTime(2014, 1, 1).AddDays(random.Next(0, 60)), 
            number % 3 == 0, RandomItem<Product>(products), random.Next(1, 100));
        return order;
    }

    T RandomItem<T>(IList<T> list) {
        int index = (int)(random.NextDouble() * 0.99 * (list.Count));
        return list[index];
    }

    void GenerateProducts() {
        products.Add(new Product("Tofu", 50));
        products.Add(new Product("Chocolade", 34));
        products.Add(new Product("Ikura", 70));
        products.Add(new Product("Chai", 3));
        products.Add(new Product("Boston Crab Meat", 36));
        products.Add(new Product("Ravioli Angelo", 18));
        products.Add(new Product("Ipon Coffee", 10));
        products.Add(new Product("Questo Cabrales", 25));
    }
}

Bind a Grid to Data

Set BindingContext for the content page to a TestOrdersRepository class instance in the MainPage.xaml.cs file, as shown below.

namespace HelloGrid {   
    public partial class MainPage : ContentPage {   
        public MainPage () {
            InitializeComponent ();

            TestOrdersRepository model = new TestOrdersRepository ();
            BindingContext = model;
        }
    }
}

To bind the grid to a data source, assign the order collection object (TestOrdersRepository.Orders) to the GridControl.ItemsSource property.

<dxGrid:GridControl x:Name="grid" ItemsSource="{Binding Orders}"> 
</dxGrid:GridControl>

Result

By default, the grid automatically generates columns for data source fields, except complex fields. In the current example, complex fields are fields of a product related to an order (Product.Name and Product.UnitPrice). The sequence of displaying columns within the grid is the same as the sequence of fields in the data source.

Grid_GettingStarted_Lesson1_Result_iOS

Grid_GettingStarted_Lesson1_Result_Android_Dark

Go on to Lesson 2 of the current Getting Started tutorial to learn how to manage a collection of grid columns (bind columns to complex fields, create an unbound column to display calculated values, adjust column settings and set the column display sequence in the grid).