tags:

views:

557

answers:

5

Hi ALL, I am binding my dropdownlist with Enum I have following enum and code for bind dropdownlist.

public enum DignosisOrderType
    {
        All = 0,
        General = 1,
        Uveitis = 2,
        Coag =3,
        PreOp=4,
        Tests=5,
        RP =6
    }

public static void BindDropDownByEnum(DropDownList dropDownList, Type enumDataSource, )
        {
            Hashtable htDataSource = new Hashtable();

            string[] names = Enum.GetNames(enumDataSource);
            Array values = Enum.GetValues(enumDataSource);

            for (int i = 0; i < names.Length; i++)
                htDataSource.Add(names[i], values.GetValue(i));

            BindDropDown(dropDownList, htDataSource, "key", "value");
        }

        public static void BindDropDown(DropDownList dropDownList, object dataSource, string dataTextField, string dataValueField)
        {
            dropDownList.DataSource = dataSource;
            dropDownList.DataTextField = dataTextField;
            dropDownList.DataValueField = dataValueField;
            dropDownList.DataBind();
        }

when the Dropdownlist is bind the data is not comming in sorting order,I want dropdownlist is bind in order of Enum is created.

A: 

One thing you could do is iterate through the HT in the BindDropDown method adding one ListItem at a time, so they would be ordered by index.

antuan
A: 

Just use SortedList or replace HashTable with SortedList

Saar
+2  A: 

A HashTable isn't the tool for the job then. Try a SortedList.

Remember, A HashTable supports very fast searching, however it does not keep any ordering

Kyle Rozendo
+3  A: 

If you want the items in the order you're adding them, you don't want a hashtable or a SortedList. (A sorted list will be fine while you actually want them in the key sort order anyway, but if you later decide you need to tweak the order, it will cause problems.) In particular, you're not trying to use the ability to look up a value by key, so you don't need an IDictionary<,> at all as far as I can see.

You just want a List<T> for a type containing the key and value. You could do that with an anonymous type, for instance:

var keyValuePairs = Enum.GetValues(enumDataSource)
                        .Select(x => new { key = x.ToString(), value = x })
                        .ToList();
BindDropDown(dropDownList, keyValuePairs, "key", "value");
Jon Skeet
I tried it , but there is no extension of ".select" that i am finding for Enum.GetValues(enumDataSource)
Vijjendra
A: 

There is actually a specialized collection called OrderedDictionary that gives you both abilities: sorting and keyed access.

Paul Sasik