有这样一个学科枚举类型:

/// 学科
/// </summary>
public enum Subject
{
None = ,
[Description("语文")]
Chinese = , [Description("数学")]
Mathematics = , [Description("英语")]
English = , [Description("政治")]
Politics = , [Description("物理")]
Physics = , [Description("化学")]
Chemistry = , [Description("历史")]
History = , [Description("地理")]
Geography = , [Description("生物")]
Biology =
}

这里使用了一个Description特性,目的是为了在一个DropDownList列表中绑定文本数据。

这里使用了一个扩展方法,目的为了返回一个Value和Text的数据列表,上方法:

/// 枚举辅助类
/// </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 > )
{
string text = string.Empty;
object[] array = field.GetCustomAttributes(typeDescription, false); if (array.Length > ) text = ((DescriptionAttribute)array[]).Description;
else text = field.Name; //没有描述,直接取值 //添加到列表
list.Add(new { Value = value, Text = text });
}
}
return list;
}
}

这里采用特性反射的方式得到了对应的Value和Text,最后返回了一个new { Value = …, Text = … }的匿名类的列表。

那么页面上实现就相当简单了:

ddlSubject.DataSource = typeof(Subject).GetItems();
ddlSubject.DataTextField = "Text";
ddlSubject.DataValueField = "Value";
ddlSubject.DataBind();

最新文章

  1. scrapy爬虫笔记(二)------交互式爬取
  2. LightOJ1283 Shelving Books(DP)
  3. Event --mysql的scheduler.md
  4. OpenCV - Operations on Arrays 对数组(矩阵)的一些操作
  5. 06链队列_LinkQueue--(栈与队列)
  6. Ubuntu下将vim配置为Python IDE(转)
  7. UC高级编程--实现myls程序
  8. 使用newtonsoft序列化
  9. POJ2387 Til the Cows Come Home 【Dijkstra】
  10. SpringIOC和AOP原理 设计模式
  11. lambda Helper
  12. vue-router-1-安装与基本使用
  13. monkey配置及简单报告生成(安卓)
  14. 关于pthread_cond_wait()使用的理解
  15. spark 调优——基础篇
  16. Excel 中 VLOOKUP() 函数小结
  17. go语言基础之二维数组
  18. ios开发遇到的问题
  19. 《java虚拟机》----虚拟机字节码执行引擎
  20. 百度编辑器(ueditor)@功能之获取坐标

热门文章

  1. 各种边框样式。。本以为border不是这么用的。
  2. Delphi Refactor 重构
  3. 负载均衡--大型在线系统实现的关键(上篇)(再谈QQ游戏百万人在线的技术实现)
  4. Scriptcase优惠活动即将结束
  5. Codeforces 118 D. Caesar&#39;s Legions (dp)
  6. LA4329 Ping pong(树状数组与组合原理)
  7. Thinkphp模板怎么使用自定义函数
  8. SVN安装与使用
  9. EasyMock使用说明
  10. Ubuntu12.10 下搭建基于KVM-QEMU的虚拟机环境(十六)