Skip to content
Tags

Useful Tip – Converting an Enum as list of values for dropdown list

January 17, 2012

An important thing I wanted to do was to convert a set of enums you have defined in your project into a set of values that can be used in a dropdown list. The tricky thing here is using the collection objects of which one to use in C#. At first I used a HashTable object to store the values in the DropDown List but the list of values was unordered, and there was no easy way of ordering it.

So the solution after finding it eventually was to use the Dictionary object. Here’s the solution which works very well, in which you use the Compare method of two ints.

EnumClass is your defined Enum objects with decalred values, and ddl is your Dropdown List variable.
Dictionary<string, int> d = GetEnumForBind(typeof(EnumClass));

List<KeyValuePair<string, int>> sList = new List<KeyValuePair<string, int>>();
sList.AddRange(d);
sList.Sort
(
delegate(KeyValuePair<string, int> kvp1,
KeyValuePair<string, int> kvp2)
{
return Comparer<int>.Default.Compare(kvp1.Value, kvp2.Value);
}
);

ddl.DataSource = d;
ddl.DataTextField = “key”;
ddl.DataValueField = “value”;

ddl.DataBind();

 

……

 

public Dictionary<string, int> GetEnumForBind(Type enumeration)
{
string[] names = Enum.GetNames(enumeration);
Array values = Enum.GetValues(enumeration);
Dictionary<string, int> d = new Dictionary<string, int>();
for (int i = 0; i < names.Length; i++)
{
d.Add(names[i].ToString(), Convert.ToInt32(values.GetValue(i)));
}
return d;
}

Advertisements

From → Uncategorized

2 Comments
  1. i love your blog, i have it in my rss reader and always like new things coming up from it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: