public enum SendInfoStateEnum
{
[Description("等待提交")]
等待提交 = 1,
[Description("等待审核")]
等待审核 = 2,
审核成功 = 3,
审核失败 = 4,
正在发送 = 5,
}
绑定枚举到dropdownlist方法如下:
调用如:BindEnumToDropdownList(typeof(SendInfoStateEnum), ddlSendState, new ListItem("--请选择--", "-1"), "-1");
重点是Enum.GetValues(enumType)、Enum.GetName(enumType, i) 2个方法。
/// <summary> /// 绑定枚举到dropdownlist /// </summary> /// <param name="enumType">枚举类型</param> /// <param name="ddl">dropdownlist</param> /// <param name="li">初始化第一个选项,可为null</param> /// <param name="selectValue">选中项的值</param> public static void BindEnumToDropdownList(Type enumType, DropDownList ddl, ListItem firstItem, string selectValue) { ddl.Items.Clear(); if (firstItem != null) { ddl.Items.Add(firstItem); } foreach (int i in Enum.GetValues(enumType)) { ListItem li2 = new ListItem(Enum.GetName(enumType, i), i.ToString()); if (li2.Value.Equals(selectValue)) { li2.Selected = true; } ddl.Items.Add(li2); } }
获取枚举值的描述标签方法:
调用如:GetDescriptionByName(SendInfoStateEnum.等待提交);
/// <summary> /// get enum description by name /// </summary> /// <typeparam name="T">enum type</typeparam> /// <param name="enumItemName">the enum name</param> /// <returns>description string</returns> public static string GetDescriptionByName<T>(this T enumItemName) { FieldInfo fi = enumItemName.GetType().GetField(enumItemName.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { return attributes[0].Description; } else { return enumItemName.ToString(); } }