5/2/2008 2:15:05 PM
This is another installment in my recent "Late Pass" series. I've been working with enums a lot lately and as I usually do in my spare time, I visit http://www.dotnetkicks.com to read up on cool stuff related to technology I am currently using. I'm wanting to bind the contents of the enum to a dropdown / radiobutton list. The first article I came across seemed like it would work. That was until I stumbled upon this article by Christopher Bennage. It's short and sweet but really helpful.
A repost of the original code:
public
static class Enum<T>
{
public static T Parse(string value)
{
return (T) Enum.Parse(typeof (T), value);
}
public static IList<T> GetValues()
{
IList<T> list = new List<T>();
foreach (var value in Enum.GetValues(typeof (T)))
list.Add((T) value);
return list;
}
}
Sample enum:
public
enum DataProvider
{
SqlServer = 1,
Access = 2,
MySql = 3,
Oracle = 4
}
Let's bind those values to a dropdownlist and let our users choose:
private
void InitializeDataProviderDropDownList()
{
selectDataProvider.DataSource = Enum<DataProvider>.GetValues();
selectDataProvider.DataBind();
}
Let's add a button and process the selected value:
DataProvider
dataProvider = Enum<DataProvider>.Parse(selectDataProvider.SelectedValue);
switch (dataProvider)
{
case DataProvider.Access:
Response.Write("Access");
break;
case DataProvider.MySql:
Response.Write("MySql");
break;
case DataProvider.Oracle:
Response.Write("Oracle");
break;
default:
Response.Write("SqlServer");
break;
}
I realize that this is a stupid use of the functionality at-hand. By this I mean if the end-result were actually to Response.Write the SelectedValue I would be going about doing it the wrong way. This would be extremely useful for methods that take an enum as a parameter. I'll definitely be using this in the future.
Easy.
C#,
Code

Comments

I`m glad the code was useful to you!
Posted by: Christopher Bennage | 5/5/2008 10:56:04 AM