Home > Mobile >  C# WPF Get Value from first Combobox and change value of second Combobox
C# WPF Get Value from first Combobox and change value of second Combobox

Time:08-24

For days I have been trying to connect two comboboxes to the mysql database, creating a primary and a secondary combobox, depending on the choice of the first combobox should return precise results in the second, I tried to use "SelectionChanged", but I can get the correct value , only after changing it a second time.

Premise before creating the post I searched a lot in google, and above all I examined several questions on the site (very old), but I can't solve

LOADER FIRST COMBOBOX:

        public void load()
        {
            MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["dbx"].ConnectionString);
            MySqlCommand cmd = new MySqlCommand("SELECT CLASSIFICATION FROM `classification`", conn);
            conn.Open();            

            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
            conn.Close();

            TipoClass.ItemsSource = dt.DefaultView;
        }

LOADER SECOND COMBOBOX:

        public void loadOne(string name)
        {
            MessageBox.Show(name);
            MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["dbx"].ConnectionString);
            MySqlCommand cmd = new MySqlCommand("SELECT DETAILS FROM `details` WHERE CLASSIFICATION = "   name, conn);
            conn.Open();            

            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
            conn.Close();

            DetailsClass.ItemsSource = dt.DefaultView;
        }

XAML.CS:

        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (TipoClass.SelectedItem != null)
            {
                string myString = TipoClass.Text;
                MessageBox.Show(myString);
            }
        }

XAML:

<ComboBox HorizontalAlignment="Left" Grid.Row="11" VerticalAlignment="Center" Width="350" Height="30" Margin="106,0,0,0" x:Name="TipoClass" DisplayMemberPath="CLASSIFICATION" SelectionChanged="SelectionChanged"/>
<ComboBox HorizontalAlignment="Left" Grid.Row="12" VerticalAlignment="Center" Width="350" Height="30" Margin="106,0,0,0"  x:Name="DetailsClass" DisplayMemberPath="DETTAGLIO"/>

CodePudding user response:

Try to call your method like this in the event handler:

private void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string selectedValue = TipoClass.SelectedItem as string;
    if (!string.IsNullOrEmpty(selectedValue))
        loadOne(selectedValue);
}
  • Related