2

Is it possible to load items from an Enum to a ComboBox in .NET 3.5?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239

2 Answers2

10

Yes.

combobox.DataSource = Enum.GetValues(typeof(SomeEnum));
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Here's some code we used on a recent project. It handles localized Enum strings (by passing in a ResourceManager object) and populates the .Items array directly instead of using a DataSource -- this is useful for populating a ComboBox, including setting its .SelectedItem, before making it or its parent controls visible.

public static void PopulateComboBox<T>(ComboBox box, ResourceManager res) {
    box.FormattingEnabled = true;
    ListControlConvertEventHandler del = delegate(object sender, ListControlConvertEventArgs e) {
        e.Value = res.GetString(e.Value.ToString());
    };
    box.Format -= del;
    box.Format += del;
    box.BeginUpdate();
    box.Items.Clear();
    foreach(T value in Enum.GetValues(typeof(T))) {
        box.Items.Add(value);
    }
    box.EndUpdate();
}

Use it like:

PopulateComboBox<MyEnum>(myComboBox, MyEnumStrings.ResourceManager);
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135