Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
1185
Populating a WinComboEditor with an enum
posted

Want to easily populate a WinComboEditor with an enum?

heres how...

In a suitable place on your form code

MyUltraComboEditor.PopulateWithEnum<

 

MeasurementTypes>();

where MeasurementTypes is defined as the following enum;

public enum MeasurementTypes
{
    [Description("each per item etc")] 
    Discreet,
    Linear,
    Area,
    Volume
}

You can also use the Description Attribute for a more verbose description of the enum value with spaces in it!

I inherited and modified the ComboEditor as such;


    public class ipUltraComboEditor : Infragistics.Win.UltraWinEditors.UltraComboEditor
    {

        public void  PopulateWithEnum<T> ()
        {
            Type enumType = typeof(T);
            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException("T must be of type System.Enum");
            string desc;

            foreach (T item in EnumToList<T>())
            {
                FieldInfo fi = item.GetType().GetField(item.ToString());
                DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false);
                if (attributes != null && attributes.Length > 0)
                    desc = attributes[0].Description;
                else
                    desc = item.ToString();
                var vli = new ValueListItem { DataValue = item, DisplayText = desc };
                this.Items.Add(vli);
            }
        }

        public static IEnumerable<T> EnumToList<T>()
        {
            Type enumType = typeof(T);

            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException("T must be of type System.Enum");

            Array enumValArray = Enum.GetValues(enumType);
            List<T> enumValList = new List<T>(enumValArray.Length);

            foreach (int val in enumValArray)
            {
                enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
            }

            return enumValList;
        }
    }

The ComboEditor can be databound  as normal and saves the integer value back to the data source.

 

Let me know if this was useful!