For the problem of populating a combobox with data from database based on the selected item of another combobox, you could try to refer to the code below.
MainWindow.xaml:
<ComboBox x:Name="categories" HorizontalAlignment="Left" Margin="52,194,0,0" VerticalAlignment="Top"
Width="324" Height="43" FontSize="24" SelectionChanged="combo_app_SelectionChanged">
</ComboBox>
MainWindow.xaml.cs:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace ComboboxSelectedBind
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
BindComboBoxApp();
}
private void BindComboBoxApp()
{
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
using (var con = new SqlConnection(@"constr"))
{
using (var command = new SqlCommand("SELECT CategoryId, Name FROM [dbo].[Categories]", con))
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
DataSet ds = new DataSet();
da.Fill(ds);
categories.ItemsSource = ds.Tables[0].DefaultView; ;
categories.DisplayMemberPath = "Name";
categories.SelectedValuePath = "CategoryId";
con.Close();
}
}
}
private void combo_app_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (categories.SelectedItem != null)
{
var a = categories.SelectedValue;
var con = new SqlConnection(@"constr");
con.Open();
var command = new SqlCommand("SELECT COUNT(*) FROM [dbo].[Categories] where CategoryId=@a", con);
command.Parameters.AddWithValue("@a", a);
var result = Convert.ToInt32(command.ExecuteScalar());
if (result > 0)
{
var cmd = new SqlCommand("SELECT ProductId, ProductName FROM [dbo].[Products] WHERE CategoryId like '" + categories.SelectedValue + "' ", con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
categories.ItemsSource = ds.Tables[0].DefaultView; ;
categories.DisplayMemberPath = "ProductName";
categories.SelectedValuePath = "ProductId";
con.Close(); }
}
}
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.