Tuesday, March 20, 2012

How to get the Key from an Enum in asp.net?

This method will return the Key or Description from an Enum Item

 /// <summary>
        /// GetDescriptionFromEnumValue is returns the name  for an Enum Item
        /// </summary>
        /// <param name="value">Enum Value</param>
        /// <returns>Description For Enum</returns>
        public static string GetDescriptionFromEnumItem(Enum value)
            DescriptionAttribute attribute = value.GetType()
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;

Here how to use this function from other class
 /// Function Name: GetComTypes
        /// Bishnu Tewary
        /// 05-03-2012
        /// <summary>
        /// GetTitleNameByValue function return the Name of an enum item for its value
        /// </summary>
        /// <param name="value"> value of the enumitem</param>
        /// <returns>name of the value</returns>
        public string GetTitleNameByValue(int value)
            TitleTypes enumItem = (TitleTypes)Enum.Parse(typeof(TitleTypes), Convert.ToString(value));
            return EnumUtility.GetDescriptionFromEnumItem(enumItem);

No comments:

Post a Comment