May 31, 2013

Convert enum to hashtable for dropdown list binding

We have one enum

enum ContractType
{
    Permanent = 1,
    Contract = 2,
    Internship = 99
}

Below function for convert enum to hashtable

public static Hashtable BindToEnum(Type enumType)
{
    // get the names from the enumeration
    string[] names = Enum.GetNames(enumType);
    // get the values from the enumeration
    Array values = Enum.GetValues(enumType);
    // turn it into a hash table
    Hashtable ht = new Hashtable();
    for (int i = 0; i < names.Length; i++)
        // note the cast to integer here is important
        // otherwise we'll just get the enum string back again
        ht.Add(names[i], (int)values.GetValue(i));
    // return the dictionary to be bound to
    return ht;
}

Now we can direct call above function for convert enum to hashtable and use for dropdown bind.


MyDropDownList.DataSource = BindToEnum(typeof(ContractType));

Hope you will help above code !!

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete