通用 Asp.Net DropDownList 绑定枚举类型 实例

/// <summary>
/// Mr.Tom 下拉列表框绑定枚举
/// </summary>
/// <param name="droplist">DropDownList名称</param>
/// <param name="enumType">要绑定的枚举类型</param>

/// <param name="li">第一项要显示的.eg:--请选择--</param>
/// <returns></returns>
public static void bindEnumList(DropDownList droplist, Type enumType, ListItem li)
{
    droplist.Items.Clear();
    if (enumType.IsEnum == false)
   {
        return;
    }
    droplist.Items.Add(li);

 

   Type typeDescription = typeof(DescriptionAttribute);
   System.Reflection.FieldInfo[] fields = enumType.GetFields();
   string strText = string.Empty;
   string strValue = string.Empty;
   foreach (FieldInfo field in fields)
   {
     if (field.IsSpecialName) continue;
     strValue = field.GetRawConstantValue().ToString();
     object[] arr = field.GetCustomAttributes(typeDescription, true);
     if (arr.Length > 0)
    {
       strText = (arr[0] as DescriptionAttribute).Description;
    }
    else
    {
       strText = field.Name;
    }

    droplist.Items.Add(new ListItem(strText, strValue));
  }

}

posted @ 2010-12-29 22:07  Mr.Tom  阅读(563)  评论(0编辑  收藏  举报