How to associate a combo box with a dataset in WPF

I want to associate a combo with a dataset and take the value from the combo as a parameter to populate another combo in WPF

+3
source share
1 answer

This should help you get started. The event Window_Loadedsets a DataTable with multiple rows and sets DataContextand DisplayMemberPathfor ComboBox. The event Countries_SelectionChangedcaptures SelectedItem(if any) and discards the property Cities.ItemsSourceas a result of calling the method that returns IEnumerable<string>. This call can be whatever you want (database call, file handling, 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[] { "" };
}
+4
source

Source: https://habr.com/ru/post/1715592/


All Articles