开发者

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

Is it possible 开发者_如何学Cto load items from an Enum to a ComboBox in .NET 3.5?


Yes.

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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜