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

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

+2


a source to share


2 answers


Yes.



combobox.DataSource = Enum.GetValues(typeof(SomeEnum));

      

+10


a source


Here is the code we used on a recent project. It handles localized Enum strings (by passing in an object ResourceManager

) and populates the array .Items

directly instead of using the DataSource - this is useful for populating ComboBox

, including setting it up .SelectedItem

before doing so or its parent controls are 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);

      

0


a source







All Articles