RoadieRich
RoadieRich

Reputation: 6586

Unable to set SelectedItem on Winforms ComboBox with DataSource

I have the following code to generate a ComboBox

BindingList<Type> types = new([typeof(Foo), typeof(Bar)]);
Type? selectedType = types.SingleOrDefault(t => t.Name == "Bar");
ComboBox comboBox1 = new()
{
    DataSource = types,
    DisplayMember = nameof(Type.Name),
    DropDownStyle = ComboBoxStyle.DropDownList,
    SelectedItem = selectedType
};

However, when I display the combobox, despite selectedType having the value I'd expect, the combobox has the first item selected. Also, I noticed that if I try to use comboB ox1.SelectedIndex, all values throw an IndexOutOfRangeException.

If I remove the DataSource assignment, and instead populate the Items property, it works fine:

BindingList<string> strings = new(new string[] { "Foo", "Bar"}.ToList());

ComboBox comboBox1 = new()
{
    DropDownStyle = ComboBoxStyle.DropDownList,
};
comboBox1.Items.AddRange(strings.ToArray());
comboBox1.SelectedItem = "Bar";

Is this a limitation of Winforms, or am I doing something wrong?

I've looked at the related questions, this one seems related, but doesn't have an answer that works for me, since I can't set the DisplayName and DisplayValue to anything.

Upvotes: 0

Views: 56

Answers (0)

Related Questions