.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Customised functions for enum to get enum description fill enum data in dropdownlist

Posted By:Rajshree       Posted Date: October 22, 2010    Points: 15    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  

Here is a Class where we are having some function.Description given below:

Here is a Class where we are having some function which is used to get description of any specific type enum ,get key value pair of specified enum and add the key value pair
in list which can be easily bind with dropdownlist wih the help of FillDropDownList Function.

    public class EnumKeyValuePairs

        ///        Returns descriptions (if available) or enum names (if not) for all
        ///        values in the specified Enum.

        /// The Enum type.
        public static string[] GetDescriptions(Type enumType)
            List values = new List();
            FieldInfo[] fieldInfos = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo fieldInfo in fieldInfos)
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0)
            return values.ToArray();

        ///        Get a dictionary containing Id/Description pairs for the supplied enum type.

        public static SortedList GetEnumKeyValuePairs(Type enumType)
            Array values = Enum.GetValues(enumType);
            string[] descriptions = GetDescriptions(enumType);

            SortedList pairs = new SortedList();
            for (int i = 0; i < values.Length; i++)
                pairs.Add((byte)values.GetValue(i), descriptions[i]);
            return pairs;

        public static void FillDropDownList(DropDownList ddl, Type enumType, string defaultValue)
            ddl.DataSource = GetEnumKeyValuePairs(enumType);
            ddl.DataTextField = "value";
            ddl.DataValueField = "key";

            if (!string.IsNullOrEmpty(defaultValue))
                ListItem item = ddl.Items.FindByValue(defaultValue);
                if (item != null)
                    if (ddl.SelectedItem != null)
                        ddl.SelectedItem.Selected = false;
                    ddl.Items.FindByValue(defaultValue).Selected = true;




Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend