public static void SetDataToEnumsPrimitive <T>(this ComboBox combo, List <T> enumValues, int min = -1, int max = -1, StringFromEnumArgs <T> getStringFromEnum = null, BoolFromEnumArgs <T> includeEnumValue = null) where T : struct, IConvertible { List <ComboItem <T> > listItems = new List <ComboItem <T> >(); enumValues.ForEach(x => { int val = Convert.ToInt32(x); if (min >= 0 && val < min) { return; } if (max >= 0 && val > max) { return; } if (includeEnumValue != null) { if (!includeEnumValue(x)) { return; } } string display = x.ToString(); if (getStringFromEnum != null) { display = getStringFromEnum(x); } listItems.Add(new ComboItem <T>() { Value = x, Display = display }); }); //Try to retrain previous selection. int selIdx = -1; //if(combo.SelectedItem!=null && (combo.SelectedItem is ComboItemIntValue)) { // selIdx=listItems.FindIndex(x => x.Value==((ComboItemIntValue)combo.SelectedItem).Value); //} BindingList <ComboItem <T> > binder = new BindingList <ComboItem <T> >(listItems); combo.DataSource = binder; combo.ValueMember = "Value"; combo.DisplayMember = "Display"; //combo.DataSource=listItems; if (selIdx >= 0) { combo.SelectedIndex = selIdx; } }
public static void SetDataToEnumsPrimitive <T>(this ComboBox combo, int min = -1, int max = -1, StringFromEnumArgs <T> getStringFromEnum = null, BoolFromEnumArgs <T> includeEnumValue = null) where T : struct, IConvertible { //Make sure the IConvertibleType is actually an enum. if (!typeof(T).IsEnum) { throw new Exception("T must be an Enum type"); } SetDataToEnumsPrimitive <T>(combo, Enum.GetValues(typeof(T)).Cast <T>().ToList(), min, max, getStringFromEnum, includeEnumValue); }