dropdownlist绑定枚举值
类别:编程学习 浏览量:589
时间:2014-6-8 dropdownlist绑定枚举值
dropdownlist绑定枚举值一、简单的方法
1、枚举定义
public enum EnumActivityType
{
Task = 1,
Fax = 2,
Phone = 3,
Email = 4,
Reminder = 5,
Appointment = 6,
Expiration = 7,
Inquiry = 8
}
2、将枚举转换成ArrayList
public static IList ListTypeForEnum()
{
ArrayList list = new ArrayList();
foreach (int i in Enum.GetValues(typeof(EnumActivityType)))
{
ListItem listitem = new ListItem(Enum.GetName(typeof(EnumActivityType), i), i.ToString());
list.Add(listitem);
}
return list;
}
3、绑定dropdownlist
private void ListType()
{
drpStatus.Items.Clear();
drpStatus.DataSource = ListTypeForEnum();
drpStatus.DataValueField = "value";
drpStatus.DataTextField = "text";
drpStatus.DataBind();
}
二、反射 + 特性 的方式实现
1、枚举
/// <summary>
/// 紧急程度
/// </summary>
public enum eOA_EmergencyLevel
{
[Description("平件")]
PinJian= 1,
[Description("急件")]
JiJian = 2
}
2、枚举扩展方法
///<summary>
/// 枚举辅助类
///</summary>
public static class EnumHelper
{
/// <summary>
/// 获得枚举类型数据项(不包括空项)
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns></returns>
public static IList<object> GetItems(this Type enumType)
{
if (!enumType.IsEnum)
throw new InvalidOperationException();
IList<object> list = new List<object>();
// 获取Description特性
Type typeDescription = typeof(DescriptionAttribute);
// 获取枚举字段
FieldInfo[] fields = enumType.GetFields();
foreach (FieldInfo field in fields)
{
if (!field.FieldType.IsEnum)
continue;
// 获取枚举值
int value = (int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null);
// 不包括空项
if (value > 0)
{
string text = string.Empty;
object[] array = field.GetCustomAttributes(typeDescription, false);
if (array.Length > 0) text = ((DescriptionAttribute)array[0]).Description;
else text = field.Name; //没有描述,直接取值
//添加到列表
list.Add(new { Value = value, Text = text });
}
}
return list;
}
}
3、绑定dropdownlist
ddlSubject.DataSource = typeof(Subject).GetItems();
ddlSubject.DataTextField = "Text";
ddlSubject.DataValueField = "Value";
ddlSubject.DataBind();
标签:枚举