a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:
comboBox1.DataSource = Enum.GetValues(typeof(MyE
Generic method for setting a enum as datasource for drop downs
Display would be name. Selected value would be Enum itself
public IList<KeyValuePair<string, T>> GetDataSourceFromEnum<T>() where T : struct,IConvertible
{
IList<KeyValuePair<string, T>> list = new BindingList<KeyValuePair<string, T>>();
foreach (string value in Enum.GetNames(typeof(T)))
{
list.Add(new KeyValuePair<string, T>(value, (T)Enum.Parse(typeof(T), value)));
}
return list;
}
public static void FillByEnumOrderByNumber<TEnum>(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select
new
KeyValuePair<TEnum, string>( (enumValue), enumValue.ToString());
ctrl.DataSource = values
.OrderBy(x => x.Key)
.ToList();
ctrl.DisplayMember = "Value";
ctrl.ValueMember = "Key";
ctrl.SelectedValue = enum1;
}
public static void FillByEnumOrderByName<TEnum>(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true ) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select
new
KeyValuePair<TEnum,string> ( (enumValue), enumValue.ToString() );
ctrl.DataSource = values
.OrderBy(x=>x.Value)
.ToList();
ctrl.DisplayMember = "Value";
ctrl.ValueMember = "Key";
ctrl.SelectedValue = enum1;
}
this is the solution to load item of enum in combobox :
comboBox1.Items.AddRange( Enum.GetNames(typeof(Border3DStyle)));
And then use the enum item as text :
toolStripStatusLabel1.BorderStyle = (Border3DStyle)Enum.Parse(typeof(Border3DStyle),comboBox1.Text);
At the moment I am using the Items property rather than the DataSource, it means I have to call Add for each enum value, but its a small enum, and its temporary code anyway.
Then I can just do the Convert.ToInt32 on the value and set it with SelectedIndex.
Temporary solution, but YAGNI for now.
Cheers for the ideas, I will probably use them when I do the proper version after getting a round of customer feedback.