0

On form load (edit action) I want to combobox be selected with appropriate value. These value is of type LangEnum.

I tried with comboBoxLanguage.SelectedValue = book.Language; but combo is always populated with default value (first from enum list).

update:

book.Language is declared as

public enum EnumLang { English = 1, German = 2, Other = 3 };

I tried both with

comboBoxLang.SelectedItem = (Book.EnumLang)book.Language;

and with

comboBoxLang.SelectedItem = book.Language;

and nothing works (default first value (English) is always set) and worth to mention is that on debug mode book.Language is set To German or Other but English is selected on combobox.

user2783193
  • 992
  • 1
  • 12
  • 37
  • What is the `value-member` of your combo? – huMpty duMpty Oct 18 '13 at 12:36
  • You say you are trying to set the value of your combobox inside the `Load` event of your Form. Have you tried to set the combobox item in another point of your code? For example inside the `Shown` event of the Form or just after the `InitializeComponent()` method call inside the Constructor of the Form? – Spaceman Oct 21 '13 at 07:21

4 Answers4

1

That looks right to me! I am doing the same thing, are you sure that book.Language string is an EXACT match to one of the items in the list?

And is the list populated BEFORE you are trying to SelectedValue?

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
0

Better try:

comboBoxLanguage.SelectedItem = book.Language;

// or even

comboBoxLanguage.Text = book.Language.ToString(); //should work

You might want to set the ValueMember property to get or set the SelectedValue.

nawfal
  • 70,104
  • 56
  • 326
  • 368
0

Works fine for me using SelectedItem:

comboBoxLanguage.SelectedItem = book.Language;
0

You didn't tell what kind of variable book is: is it of type LangEnum? Or is it a class with a Language property? (in this last case: what is the type of the Language property?)

If book is of type LangEnum you can use the SelectedItem property as others have said. (Check this SO question if you need more informations of the differences between the two combobox properties) Otherwise you'll probably need a cast:

comboBoxLanguage.SelectedItem = (LangEnum)book.Language;

Moreover, if you are populating your combobox inside a WinForm event, you should also care about the order in which they are fired. Take a look at this SO question form more infos.

Community
  • 1
  • 1
Spaceman
  • 547
  • 8
  • 25