I've been working more with data-binding and the ObjectBindingSource component that
I wrote about here. Here is some stripped-down sample code to help investigate more data-binding concepts.
class Customer {
int Id;
BindingList Orders;
}
class Order {
int OrderNumber;
Product ProductInfo;
}
class Product {
string Vendor;
Product Self;
}
Assume that we want individual GUI components for the Customer object, and a grid to display the associated orders, with the related Product information displayed along with the Order. Here are some quick pseudo-code tips to get things wired up properly.
- CustomerObjectBindingSource.DataSource = typeof(Customer)
- CustomerObjectBindingSource.BindableProperties.Add("Orders"). (If you don't do this, the detail ObjectBindingSource won't work later on.)
- OrdersObjectBindingSource.DataSource = CustomerObjectBindingSource and OrdersObjectBindingSource.DataMember = "Orders"
- OrdersObjectBindingSource.BindableProperties.Add("Product")
- DataGridView.DataSource = OrdersObjectBindingSource
- Modify the DataGridView column for Product by setting:
- column.DataSource = ProductsBindingSource
- column.DisplayMember = "Name"
- column.ValueMember = Self
- **IMPORTANT** - Use the same object references everywhere for the product objects (i.e. in the DataGridView column and where you access them in your code). In the sample, I use the productBindingSource component for both the lookup in the grid and the way to lookup individual Product instances. Another alternative that I tested is to use a singleton class for the collection. If you don't do this, you will get the dreaded "DataGridViewComboBoxCell value is not valid" error when the grid tries to populate the Product value.
For concrete details, download this project. I look forward to your comments.