Populate drop down list from enum in ASP.NET web form

Drop down list is used to show various items on the user interface to select one from them. It is very useful specially when we have not much space in the user interface. When user click on the list then it drop with all the information, from which one can be selected. It is so common to populate a drop down list from database data. But in other case we need to populate it from other source also, like an enum. So how do we populate a drop down list from an enum?

To show you an example. Suppose we have an enum called Departments. Now we want to show all the departments which is in the enum to drop down list in our user interface, so that user can choose a department from there. If you search the internet, you can find many ways to do this. I use this approach to solve one of my requirement today.

enum Departments
{
    Software,
    Marketing,
    HR,
    TalentHunting
}
string[] departmentNames = Enum.GetNames(typeof(Departments));

foreach (string departmentName in departmentNames)
{
    Departments department = 
        (Departments)Enum.Parse(typeof(Departments), departmentName);
    int departmentValue = (int)department;

    ListItem liDepartment = new ListItem() 
    { 
        Text = departmentName, 
        Value = departmentValue.ToString() 
    };
    ddlDepartments.Items.Add(liDepartment);
}
Populate drop down list from enum
Drop down list

The System.Enum class has some good utility methods to work with enums. I use two of them today.

public abstract class Enum : 
    ValueType, IComparable, IFormattable, IConvertible
{
    // Retrieves an array of the names of the constants 
    // in a specified enumeration.
    public static string[] GetNames(Type enumType);
    
    // Converts the string representation of the name or 
    // numeric value of one or more enumerated constants 
    // to an equivalent enumerated object.
    public static object Parse(Type enumType, string value);

    //...
}

I recomand you to play with System.Enum class so that you can understand how to solve your recuirments with enum. If you have other good solution to populate drop down list from enum please let me know.

Advertisements

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