Master detail combo boxes in windows forms

An application I was working on today required two comboboxes to be linked as parent and child (master and slave). Changing the selection on the first combobox needed to cause the second box to provide choices from a child table. For example, the first box could be a list of country codes and the second box could be a list of states or provinces within the country.

It had been a while since I had done winforms development but the .net environment gives great support for this kind of shared state through the binding manager and so I was expecting it to be easy - set the datasource and then the display member and we're done. Oh right, I then remembered that I would have to use the relationship between the parent and child tables to control the slave combobox. Then I got stuck on what to set in the the datasource and display member properties. The last time I did this I think I used datagrids and that was what I thought of trying first. For a datagrid, the answer looks something like this:

datagrid1.DataSource = ds;

datagrid1.DataMember = ds.Relations["parent_child"];

Where parent_child is the name of the relation between the two tables. But there is no DataMember property on the combobox and, come to think of it, how would the combobox know what column I wanted? So after some experiments and some searching around the web I found what I needed to make it work in Dino Esposito's article: http://www.devx.com/codemag/Article/22028/1954?pf=true. I tried setting the DataSource to the data set and the DisplayMember to the path of the column on the child like this:

combobox2.DataSource = ds;

comboBox2.DisplayMember = "parent.parent_child.childCol1";

This nearly worked, the second combobox now displayed data from the child table but it did not change when I changed the parent. Here is what the parent looked like:

combobox1.DataSource = ds.Tables["parent"];

combobox1.DisplayMember = "parentCol1";

The problem was that the binding context set up a different manager for the two controls because their datasources were different. By changing the parent to:

combobox1.DataSource = ds;

combobox1.DisplayMember = "parent.parentCol1";

Now they shared the same binding manager and the controls worked as required.

Hope this saves you some time.