2014-06-15 99 views
0

我有一套在.cs文件中定義的枚舉,我想將這些枚舉綁定到aspx頁面的下拉列表中。我需要在4位顯示該下拉列表。有人可以幫助嗎?綁定枚舉以下拉列表

+0

可能重複[?如何綁定枚舉類型的DropDownList的(http://stackoverflow.com/questions/3098623/how-to-bind-enum-types-to-the-dropdownlist) –

回答

1

使用下面的代碼綁定下拉與enum

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

如果你想選擇的值

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

附加在一個下拉2枚舉的項目,你可以

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

我有3枚枚舉,我希望在列表中列出2個列表。我怎麼能夠? – user3356020

+0

@ user3356020檢查更新的代碼 –

0

做選定的綁定到列表中的特定項目的最佳方法是使用屬性。因此,創建可在特定的項目在枚舉應用屬性:

public class EnumBindableAttribute : Attribute 
{ 
} 

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

我已指定屬性的項目1和項目3,現在我可以使用所選的項目是這樣的(你可以概括如下代碼) :

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; 
    }