如果我有以下枚舉如何將枚舉類型綁定到DropDownList?
public enum EmployeeType
{
Manager = 1,
TeamLeader,
Senior,
Junior
}
,我有DropDownList的,我想這個EmployeeType
枚舉綁定到DropDownList的,有沒有辦法做到這一點?
如果我有以下枚舉如何將枚舉類型綁定到DropDownList?
public enum EmployeeType
{
Manager = 1,
TeamLeader,
Senior,
Junior
}
,我有DropDownList的,我想這個EmployeeType
枚舉綁定到DropDownList的,有沒有辦法做到這一點?
,如果你有一個名爲DropDownList的對象的DDL,你可以做到這一點,如下
ddl.DataSource = Enum.GetNames(typeof(EmployeeType));
ddl.DataBind();
,如果你想枚舉值回選擇....
EmployeeType empType = (EmployeeType)Enum.Parse(typeof(EmployeeType), ddl.SelectedValue);
我寫了一個輔助函數給我一本我可以綁定的字典:
public static Dictionary<int, string> GetDictionaryFromEnum<T>()
{
string[] names = Enum.GetNames(typeof(T));
Array keysTemp = Enum.GetValues(typeof(T));
dynamic keys = keysTemp.Cast<int>();
dynamic dictionary = keys.Zip(names, (k, v) => new {
Key = k,
Value = v
}).ToDictionary(x => x.Key, x => x.Value);
return dictionary;
}
你可以使用lambda表達式
ddl.DataSource = Enum.GetNames(typeof(EmployeeType)).
Select(o => new {Text = o, Value = (byte)(Enum.Parse(typeof(EmployeeType),o))});
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
或LINQ
ddl.DataSource = from Filters n in Enum.GetValues(typeof(EmployeeType))
select new { Text = n, Value = Convert.ToByte(n) };
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
下面是另一種方法:
Array itemNames = System.Enum.GetNames(typeof(EmployeeType));
foreach (String name in itemNames)
{
//get the enum item value
Int32 value = (Int32)Enum.Parse(typeof(EmployeeType), name);
ListItem listItem = new ListItem(name, value.ToString());
ddlEnumBind.Items.Add(listItem);
}
我用這個鏈接做到這一點:
http://www.codeproject.com/Tips/303564/Binding-DropDownList-Using-List-Collection-Enum-an
輕微錯字在lambda表達式示例(錯過了一個結束捲曲托架)。 ddl.DataSource = Enum.GetNames(typeof(EmployeeType))。 Select(o => new {Text = o,Value =(byte)(Enum.Parse(typeof(EmployeeType),o))}); – wloescher 2015-04-30 21:05:06