How to bind a ListBox to a property of type List on an object?
.net, data-binding, winforms
Solution
You can use a linked `BindingSource`. A full example is below, but the only interesting bit is:
BindingSource outer = new BindingSource(customers, ""),
inner = new BindingSource(outer, "Orders");
here's the code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
class Order
{
public string OrderRef { get; set; }
public override string ToString() {
return OrderRef;
}
}
class Customer
{
public string Name {get;set;}
public Customer() { Orders = new List<Order>(); }
public List<Order> Orders { get; private set; }
}
static class Program
{
[STAThread]
static void Main()
{
List<Customer> customers = new List<Customer> {
new Customer {Name = "Fred", Orders = {
new Order { OrderRef = "ab112"},
new Order { OrderRef = "ab113"}
}},
new Customer {Name = "Barney", Orders = {
new Order { OrderRef = "ab114"}
}},
};
BindingSource outer = new BindingSource(customers, ""),
inner = new BindingSource(outer, "Orders");
Application.Run(new Form
{
Controls =
{
new DataGridView {
Dock = DockStyle.Fill,
DataSource = outer},
new ListBox {
Dock = DockStyle.Right,
DataSource = inner
}
}
});
}
}
Problem
I have a form with a DataGridView showing a list of customers, and some text boxes below showing details of the customer selected in the grid. I have a Customer class and a CustomerList class of Customer objects, and a BindingSource with DataSource set to a CustomerList. The DataSource of the grid is this BindingSource. Binding the textboxes is easy - I just use the same BindingSource and specify the property of Customer I want to display. The problem is that one of the properties of Customer is a list itself, and I want to display this list in e.g. a ListBox. How can I accomplish showing this list in a ListBox using databinding, and have the list updated each time I click on a customer in the grid?