Hi,
I want to bind the combo with dataset and take the value from combo as parameter to populate another combo in WPF
Hi,
I want to bind the combo with dataset and take the value from combo as parameter to populate another combo in WPF
This should get you started. The Window_Loaded
event sets up a DataTable with a couple of rows, and sets the DataContext
and DisplayMemberPath
of a ComboBox
. The Countries_SelectionChanged
event grabs the SelectedItem
(if there is any) and resets the Cities.ItemsSource
property to be the result of a method call, which returns an IEnumerable<string>
. This call can be whatever you want (database call, file operation, etc.). Hope this helps!
<UniformGrid Rows="2" Columns="2">
<Label Content="Countries" VerticalAlignment="Center"/>
<ComboBox Name="Countries" VerticalAlignment="Center" SelectionChanged="Countries_SelectionChanged" ItemsSource="{Binding}"/>
<Label Content="Cities" VerticalAlignment="Center"/>
<ComboBox Name="Cities" VerticalAlignment="Center"/>
</UniformGrid>
private void Window_Loaded(object sender, RoutedEventArgs e) {
DataTable dt = new DataTable();
dt.Columns.Add("Country", typeof(string));
DataRow firstRow = dt.NewRow();
DataRow secondRow = dt.NewRow();
firstRow["Country"] = "USA";
secondRow["Country"] = "Italy";
dt.Rows.Add(firstRow);
dt.Rows.Add(secondRow);
Countries.DisplayMemberPath = "Country";
Countries.DataContext = dt;
}
private void Countries_SelectionChanged(object sender, SelectionChangedEventArgs e) {
DataRowView dr = Countries.SelectedItem as DataRowView;
if (dr != null) {
Cities.ItemsSource = null;
Cities.ItemsSource = GetCities(dr["Country"].ToString());
}
}
private IEnumerable<string> GetCities(string country) {
if (country == "USA")
return new []{ "New York", "Chicago", "Los Angeles", "Dallas", "Denver" };
if (country == "Italy")
return new[] { "Rome", "Venice", "Florence", "Pompeii", "Naples" };
return new[] { "" };
}