C# - 20 - Parent/child combobox binding

[C# 3.5]

From time to time you have 2 sets of related data to display in comboboxes. Binding the first combobox to a table is easy enough but how do you bind the second combobox in such a way that it automatically updates itself when the first combobox changes? The solution is create a DataRelation and bind to that.

In this example we are using Nations and States … select a nation in the first combobox and the second combobox should list only those states that are in that nation.

First, lets set up a dataset:

So our nations table with have a nation code and name, and our states table with have a state code and name plus the code of the nation to which it belongs.

Assume we have just populated these tables somehow. Next we need to create a relationship between these two tables. Also, for reasons I'll explain later, we need to create a blank dummy row in the child (state) table for each parent (nation) that doesn't have any children. Finally, don't forget to accept changes.

Now we are ready to bind to our comboboxes:

If you test this you will see that everytime you change the nation combobox the list of states in the state combobox changes. If there are no related states then the state combobox will be empty. But what would have happened if we hadn't created those dummy rows for childless parents? Without them when a nation without related states is picked the state combobox won't refresh but leave the previously displayed nation's states.


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License