Master-detail data binding

Demonstration of grid working with с dataset that has multiple tables linked by data relation. Processing of selected rows and their synchronization in both grids via CurrencyManager.

The grid supports data tables in DataSet linked by a data relation. When the grid connects to such data tables, it can synchronize its state and control the current position with CurrencyManager that is the part of Framework 2.0

Connection to tables is done via Grid.DataSource and Grid.DataMember. When the grid connects to a table, it enables automatic column generation.

public void Populate(Grid grid1, Grid grid2)
{
    DataSet dataSet = CreateDataSet();

    //Create "Customers" data source
    BindingSource source1 = new BindingSource();
    source1.DataSource = dataSet;
    source1.DataMember = "Customers";

    //Create "Orders" data source
    BindingSource source2 = new BindingSource();
    source2.DataSource = source1;
    source2.DataMember = "myrelation";

    //Bind grid1 to the "Customers" data source
    grid1.Headers.AutoGenerate = true;
    grid1.DataSource = source1;

    //Bind grid2 to the "Orders" data source
    grid2.Headers.AutoGenerate = true;
    grid2.DataSource = source2;
}

public static DataSet CreateDataSet()
{
    // create a DataSet with one table, two columns
    DataSet dataSet = new DataSet();

    // create Customer table
    DataTable table = new DataTable("Customers");
    dataSet.Tables.Add(table);
    table.Columns.Add("customerId", typeof (int)).AutoIncrement = true;
    table.Columns.Add("name", typeof (string));
    table.PrimaryKey = new DataColumn[] {table.Columns["customerId"]};

    // create Orders table
    table = new DataTable("Orders");
    dataSet.Tables.Add(table);
    table.Columns.Add("orderId", typeof (int)).AutoIncrement = true;
    table.Columns.Add("customerId", typeof (int));
    table.Columns.Add("amount", typeof (double));
    table.PrimaryKey = new DataColumn[] {table.Columns["orderId"]};

    // create relation
    dataSet.Relations.Add("myrelation", dataSet.Tables["Customers"].Columns["customerId"], dataSet.Tables["Orders"].Columns["customerId"]);

    //Populate data source with some data
     Random r = new Random();

    // populate the tables
    int orderId = 1;
    const int customerCount = 10;
    const int ordersPerCustomer = 5;
    for (int customerId = 1; customerId <= customerCount; customerId++)
    {
        // add customer record
        dataSet.Tables["Customers"].Rows.Add(new object[] {customerId, string.Format("customer{0}", customerId)});
    }

    for (int order = 1; order <= customerCount * ordersPerCustomer; order++)
    {
        // add order record
        dataSet.Tables["Orders"].Rows.Add(new object[] { orderId++, 1 + r.Next() % customerCount, (10 + r.Next() % 10)});
    }

    return dataSet;
}