绑定枚举到下拉列表
本文关键字:下拉列表 枚举 绑定 | 更新日期: 2023-09-27 18:08:52
我在。cs文件中定义了一组枚举,我想将这些枚举绑定到aspx页面中的下拉列表。我需要在4个地方显示下拉列表。有人能帮帮忙吗?
使用以下代码将下拉菜单与enum
绑定
drp.DataSource = Enum.GetNames(typeof(MyEnum));
drp.DataBind();
如果你想获得选中的值
MyEnum empType= (MyEnum)Enum.Parse(drp.SelectedValue);
要在一个下拉列表中添加两个枚举的项,可以
drp.DataSource = Enum.GetNames(typeof(MyEnum1)).Concat(Enum.GetNames(typeof(MyEnum2)));
drp.DataBind();
将选定的绑定到列表中的特定项的最佳方法是使用属性。因此,创建一个可以应用于枚举中的特定项的属性:
public class EnumBindableAttribute : Attribute
{
}
public enum ListEnum
{
[EnumBindable]
Item1,
Item2,
[EnumBindable]
Item3
}
我已经在Item1和Item3上指定了属性,现在我可以像这样使用选中的项目(您可以概括以下代码):
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;
}