In the code behind the page, we are going to load all the
data to the countries’ list box from an XML file, already populated with some
country names. Listing 1 below shows how to populate the country list box
Listing 2: Populate Country ListBox
// Load data into Country List box
if (!Page.IsPostBack)
{
// Load data from XML into a DataSet
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("countries.xml"));
this.lstCountry.DataSource = ds.Tables[0].DefaultView;
this.lstCountry.DataTextField = "name";
this.lstCountry.DataBind();
}
In this stage when the page runs, the user can select a
country as shown in the Figure 2.
Figure 2
Now, when the user selects a country the country listbox
event handler will be fired.
It will fill the item selected in the country Textbox.
Then it loads the cities' data from a sample XML file data
and filters the data so that only cities of the selected country will be
selected.
Listing 3 shows the country ListBox event handler.
Listing 3
private void lstCountry_SelectedIndexChanged(object sender, EventArgs e)
{
// Set the value in the textbox
this.txtCountry.Text = this.lstCountry.SelectedValue;
// Load and Filter the lstCity
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("cities.xml"));
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = "country = '" + this.lstCountry.SelectedValue + "'";
// Bind lstCity
this.lstCity.DataSource = dv;
this.lstCity.DataTextField = "name";
this.lstCity.DataBind();
}
The user is now able to select a city out of a set of cities
of the country he/she has chosen. Figure 3 shows this scenario.
Figure 3
The event handler of the city Listbox does nothing except
place the selected city in the Texbox.
In the project we have been working on, we have used the
free MagicAjax Panel so that all the post backs done when selecting values from
ListBoxes are done in an asynchronous fashion and the results are great. To get
more information about MagicAjax, visit their website at http://www.magicajax.net.