简体   繁体   中英

Populating textbox with mysql data values from combobox selection c#

I am trying to populate my text boxes with the values in my database so when a user selects a name of a teacher from the combobox, the text-boxes will populate with their contact details. This is the code I have so far. There are no errors however the textboxes are still blank when I select a value from combo box.

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MySqlConnection cs = new MySqlConnection(connectionSQL);
        cs.Open();

        DataSet ds = new DataSet();

        MySqlDataAdapter da = new MySqlDataAdapter("Select * from Teacher WHERE name='" + comboBox1.Text + "'", cs);

        MySqlCommandBuilder cmd = new MySqlCommandBuilder(da);

        da.Fill(ds);


        if (comboBox1.SelectedIndex > 0)
        {


            NameBox.Text = ds.Tables[0].Rows[0]["name"].ToString();
            AddressBox.Text = ds.Tables[0].Rows[0]["address"].ToString();

        }

Any help or advice would be greatly appreciated

I've got to believe that based on your code the problem lies right here:

if (comboBox1.SelectedIndex > 0)

if you only had one item in the list or the user selected the first item, the query would run but the text boxes wouldn't populate.

AddressBox.DataBind();
NameBox.DataBind();

You're querying the database before you verify the selected index and you should be checking for a selected index greater than -1, not 0.

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox1.SelectIndex < 0) 
    {
        // Don't want to suffer database hit if nothing is selected
        // Simply clear text boxes and return
        NameBox.Text = "";
        AddressBox.Text = "";
    }
    else 
    {
        MySqlConnection cs = new MySqlConnection(connectionSQL);
        cs.Open();

        DataSet ds = new DataSet();

        // You only need to select the address since you already have the name unless 
        // they are displayed differently and you want the database display to show
        MySqlDataAdapter da = new MySqlDataAdapter("Select address from Teacher WHERE name='" + comboBox1.Text + "'", cs);

        MySqlCommandBuilder cmd = new MySqlCommandBuilder(da);

        da.Fill(ds);

        NameBox.Text = comboBox1.Text;
        AddressBox.Text = ds.Tables[0].Rows[0]["address"].ToString();
    }
}

Also, if the name is displayed differently in the combo box than in the database in a way that's easy to miss, such as an extra space between first and last name or something else that's hard to visibly detect, that could be causing the query to not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM