user3356020
user3356020

Reputation: 119

Binding Enums to Drop down list

I have a set of Enums defined in .cs file and I wanted to bind these Enums to a drop down list in a aspx page. I need to display that dropdown list in 4places. can someone help on this?

Upvotes: 0

Views: 82

Answers (2)

Avneesh
Avneesh

Reputation: 654

The best way to do the selected binding to specific items in the list is using attributes. So create an attribute that can be applied on specific Items in the enum:

 public class EnumBindableAttribute : Attribute
{
}

public enum ListEnum
{
    [EnumBindable]
    Item1,
    Item2,
    [EnumBindable]
    Item3
}

I have specified the attribute on the Item1 and Item3, Now I can use the selected items like this ( You can generalise the following code):

protected void Page_Load(object sender, EventArgs e)
    {
        List<string> list =  this.FetchBindableList();
        this.DropDownList1.DataSource =  list;
        this.DropDownList1.DataBind();

    }

    private List<string> FetchBindableList()
    {
        List<string> list = new List<string>();
        FieldInfo[] fieldInfos = typeof(ListEnum).GetFields();
        foreach (var fieldInfo in fieldInfos)
        {
            Attribute attribute = fieldInfo.GetCustomAttribute(typeof(EnumBindableAttribute));
            if (attribute != null)
            {
                list.Add(fieldInfo.Name);
            }
        }
        return list;
    }

Upvotes: 0

Rashmin Javiya
Rashmin Javiya

Reputation: 5222

Use the following code to bind dropdown with enum

drp.DataSource = Enum.GetNames(typeof(MyEnum));
drp.DataBind();

And if you want to get the selected value

MyEnum empType= (MyEnum)Enum.Parse(drp.SelectedValue); 

To Append items of 2 enum in one dropdown you can

drp.DataSource = Enum.GetNames(typeof(MyEnum1)).Concat(Enum.GetNames(typeof(MyEnum2)));
drp.DataBind();

Upvotes: 1

Related Questions