Load ComboBox from a MySQL table - Manipulate key and other field

0

I have a table with the following structure:

+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| idLocalidade   | int(11)     | NO   | PRI | NULL    |       |
| localidadeNome | varchar(45) | NO   |     | NULL    |       |
+----------------+-------------+------+-----+---------+-------+

In XAML a ComboBox;

<ComboBox x:Name="selecaoComboBox"  Grid.Row="2" Grid.Column="1" Margin="5" SelectionChanged="selecaoComboBox_SelectionChanged"  />

I load the table data into the ComboBox in this way:

    private void carregarComboBox()
    {
        MySqlConnection ligacaoBD = new MySqlConnection(ConfigurationManager.ConnectionStrings["stringDeLigacaoDB"].ConnectionString);
        try
        {
            ligacaoBD.Open();
            var dataAdapter = new MySqlDataAdapter("SELECT idLocalidade, localidadeNome FROM localidade", ligacaoBD);
            DataSet ds = new DataSet();
            dataAdapter.Fill(ds, "localidade");
            DataTable dt = ds.Tables[0];
            selecaoComboBox.ItemsSource = ((IListSource)dt).GetList();
            selecaoComboBox.DisplayMemberPath = "localidadeNome";
            selecaoComboBox.SelectedValuePath = "idLocalidade";
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            ligacaoBD.Close();
        }
    }

Next, I want to populate two TextBoxes with the data of each record, whenever a value is selected in the ComboBox. The incomplete version is this:

    private void selecaoComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        idLocalidadeTextBox.Text = selecaoComboBox.SelectedValue.ToString();
        localidadeNomeTextBox.Text = selecaoComboBox.Text;
    }

The idLocality field I get, but it no longer applies to the LocationName field, which is an empty string! What fails in this approach?

    
asked by anonymous 04.12.2016 / 17:50

1 answer

0

From the solutions I found this one seemed simpler to me. Just change the event handler:

    private void selecaoComboBox_DropDownClosed(object sender, System.EventArgs e)
    {
        if (selecaoComboBox.SelectedIndex > -1)
        {
            idLocalidadeTextBox.Text = selecaoComboBox.SelectedValue.ToString();
            localidadeNomeTextBox.Text = selecaoComboBox.Text;
        }
    }

I just did not realize why the selectionComboBox.Text would always fetch the previous value from the initial example!

    
04.12.2016 / 19:37