This is probably easiest done by creating a
DataSet
with two
DataTable
, Countries and States, with a relation in between.
Then you use two
BindingSource
, one for Countries and one for States, that you use as
DataSource
for your combo boxes.
The code below is written for a Windows Form with two regular
ComboBox
controls, but the principal is the same for your case.
Only the last part of the code where the combo boxes are assigned the data sources should differ.
DataSet dsData = new DataSet("CountriesAndStates");
DataTable dtCountries = dsData.Tables.Add("Countries");
DataColumn dcPK = dtCountries.Columns.Add("CountryID", typeof(int));
dtCountries.Columns.Add("Name", typeof(string));
dcPK.AutoIncrement = true;
dtCountries.PrimaryKey = new DataColumn[] { dcPK };
DataTable dtStates = dsData.Tables.Add("States");
dtStates.Columns.Add("Name", typeof(string));
DataColumn dcFK = dtStates.Columns.Add("CountryID", typeof(int));
dsData.Relations.Add("Country_State", dcPK, dcFK);
DataRow drParent = null;
drParent = dtCountries.NewRow();
drParent["Name"] = "USA";
dtCountries.Rows.Add(drParent);
dtStates.Rows.Add("Alabama", drParent["CountryID"]);
dtStates.Rows.Add("Alaska", drParent["CountryID"]);
dtStates.Rows.Add("Utah", drParent["CountryID"]);
drParent = dtCountries.NewRow();
drParent["Name"] = "Canada";
dtCountries.Rows.Add(drParent);
dtStates.Rows.Add("Alberta", drParent["CountryID"]);
dtStates.Rows.Add("British Columbia", drParent["CountryID"]);
dtStates.Rows.Add("Quebec", drParent["CountryID"]);
BindingSource bsCountries = new BindingSource(dsData, "Countries");
BindingSource bsStates = new BindingSource(bsCountries, "Country_State");
cbCountries.DataSource = bsCountries;
cbCountries.DisplayMember = "Name";
cbStates.DataSource = bsStates;
cbStates.DisplayMember = "Name";
I tried to do an implementation of this in WPF as well, but being a total newbie to this technology I found it a bit difficult.
In other words, I failed miserably. :-(
And no more time today.