Can't set Combobox SelectedItem, Value

Schoof picture Schoof · Mar 19, 2012 · Viewed 10.5k times · Source

In my application I have a customer who can have multiple locations. When you select a customer in my dropdownbox, it will load comboboxes in a flowlayoutpanel with all it's locations.

This is my code for this:

        IEnumerable<locatie> opstapPlaatsen = Database.getOpstapplaatsen(klant.klant_id);

        foreach (locatie opstapplaats in opstapPlaatsen)
        {

            if (opstapPlaatsen.Count() <= 0)
            {

            }
            else
            {
                ComboBox cbbOpstap = new ComboBox();
                cbbOpstap.Width = 200;
                cbbOpstap.Height = 20;

                cbbOpstap.DataSource = Database.getLocaties();
                cbbOpstap.ValueMember = "locatie_id";
                cbbOpstap.SelectedValue = opstapplaats.locatie_id;
                cbbOpstap.SelectedItem = opstapplaats;
                cbbOpstap.DisplayMember = "FullAdress";

                flpOpstapplaats.Controls.Add(cbbOpstap);
            }
        }

My problem is that I can't set the SelectedItem or/and Value. When I look with breakpoints there is a value in opstapplaats.locatie_id (the correct one), but SelectedValue stays null.

I do something alike outside of a loop, and for a combobox not created in code, and it works there.

Alike code, but working

I have no idea what's causing this? Is this because it's in a foreach, because I used it before out of a foreach and then it worked.

Answer

Schoof picture Schoof · Mar 28, 2012

Turns out you have to first add the control to the panel, and then set the ValueMember, DisplayMember...

ComboBox cbbOpstap = new ComboBox();

cbbOpstap.Width = 200;
cbbOpstap.Height = 20;

flpOpstapplaats.Controls.Add(cbbOpstap);

cbbOpstap.ValueMember = "locatie_id";
cbbOpstap.DisplayMember = "FullAdress";
bbOpstap.DataSource = LocatieManagement.getLocaties();  

cbbOpstap.SelectedValue = opstapplaats.locatie_id;
cbbOpstap.SelectedItem = opstapplaats;

Then it works, I hope this can help somebody!