Jim Sundqvist
Jim Sundqvist

Reputation: 160

Populate a Combobox with another Combobox dynamically

I'm trying to populate a combobox with another combobox but something is wrong when changing values.

When i select an item in combobox1, it loads the values from the database as it should to combobox2, but when i then select another item in combobox1, combobox 2 show values from both my first and second item.

I need combobox2 to "forget" the first values and then show the next values once i change the item in combobox1.

Any idea how to achieve this?

Code below:

private void Cbx_ManageMedia_SelectedIndexChanged(object sender, EventArgs e)
{ //Index change for combobox1

string query = "SELECT image FROM images WHERE type = '" + MIM + "'";
//MIM = Combobox1 value

MySqlConnection conDB = new MySqlConnection(connString);
MySqlCommand cmdDB = new MySqlCommand(query, conDB);
MySqlDataReader cReader;

try
{
    conDB.Open();
    cReader = cmdDB.ExecuteReader();

    while (cReader.Read())
    {
         string image = cReader.GetString("image");
         Cbx_ManageImagesImage.Items.Add(image);
    }
}
catch (Exception ex)
{
    throw ex;
}
}

Upvotes: 0

Views: 1702

Answers (1)

Jacob Lambert
Jacob Lambert

Reputation: 7679

You first need to clear the existing items out of the combobox. If you change the first part of your code to read:

    private void Cbx_ManageMedia_SelectedIndexChanged(object sender, EventArgs e)
    { //Index change for combobox1

    Cbx_ManageImagesImage.Items.Clear() //THIS LINE HAS BEEN ADDED
    string query = "SELECT image FROM images WHERE type = '" + MIM + "'";
    .......

all of the items will be cleared out of the combo box prior to adding in new items.

Upvotes: 1

Related Questions