Monday, 6 May 2013

Fill Dropdown list with Enum with key and value

I will explain how to fill Dropdown list with Enum.

I created a class called CommonFunctions in it I created an Enum called Sports.

public class CommonFunctions
{
public enum Sports
    {
        Cricket = 0,
        Football = 1,
        Hockey = 2
    }
}

I am using this Enum to bind the Dropdown on my webpage using the following method.

public void FillDrpSport()
    {       
        foreach (CommonFunctions.Sports r in Enum.GetValues(typeof(CommonFunctions.Sports)))
        {
            ListItem item = new ListItem(Enum.GetName(typeof(CommonFunctions.Sports), r), 
                                    r.GetHashCode().ToString());
            drpSports.Items.Add(item);
        }
    }

Now call this method to your pageload event.

No comments:

Post a Comment