Load Combobox from a Mysql table - Manipulate key and other field

Asked

Viewed 401 times

1

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"  />

Load table data to Combobox 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 fill two Textbox with the data of each record, whenever a value is selected in 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 can get, but it no longer applies to the Name locale field, which is an empty string! What fails in this approach?

  • Strange! When selecting an item for the second time, I see the text of the previous.

1 answer

0

Of the solutions I found this seemed the simplest. Just changing 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 haven’t figured out why ComboBox.Text would always find the previous value in the initial example!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.