When selecting a certain value in the combobox, insert values in another

Asked

Viewed 79 times

-1

I would like to enter values in combobox 2 depending on the choice in combobox 2.

I have this code but it does not work or insert the desired values in the combobox 2.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex = 1)
    {
        comboBox2.Items.Add(new Item("Blue", 1));
    }          
}

2 answers

1

There is no way of knowing what mistake you are making. The question does not show enough details for this.

So I’m going to show you a minimal and complete working example.

In the Load of the Form I filled the first combobox and set the DisplayMember and ValueMember.

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DataSource = new[]
    {
        new { Id = 1, Nome = "Item 0" },
        new { Id = 1, Nome = "Item 1" }
    }.ToArray();

    comboBox1.DisplayMember = comboBox2.DisplayMember = "Nome";
    comboBox1.ValueMember = comboBox2.ValueMember = "Id";
}

The SelectedIndexChanged is practically the same, I just corrected the syntax error you have in the question (are two signs of equal, not one) and I took that class Item because I don’t know how it was defined.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex == 1)
    {
        comboBox2.Items.Add(new { Id = 1, Nome = "Item 2" });
    }
}

See a working GIF

  • Thank you, it worked perfectly

  • @Cesargoulart great. For the record: you can mark the answer as correct using the V on her left side

0


Apparently your code is correct, I believe it’s the problem in the if

if (comboBox1.SelectedIndex == 1)
{
    comboBox2.Items.Add(new Item("Blue", 1));
}  

Using to compare in if is ==.

And to add on the combobox, this is how:

comboBox1.Items.Add("Tokyo");  

Take a look at this link, change the way to add too.

Take the test, and report to me.

Browser other questions tagged

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