嘗試通用實現:
public static List<KeyValuePair<string, string>> EnumToList<T>() where T: Enum
{
var pInfos = typeof(T).GetFields();
List<KeyValuePair<string, string>> displayList = new List<KeyValuePair<string, string>>();
foreach (var pi in pInfos)
{
if (pi.FieldType == typeof(int)) continue;
var attr = pi.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attr != null && attr.Length > 0)
{
var key = pi.Name;
var value = (attr[0] as DisplayAttribute).Description;
KeyValuePair<string, string> listItem = new KeyValuePair<string, string>(key, value);
displayList.Add(listItem);
}
else
{
KeyValuePair<string, string> listItem = new KeyValuePair<string, string>(pi.Name, pi.Name);
displayList.Add(listItem);
}
}
return displayList;
}
數據綁定方法:
protected void Page_Load(object sender, EventArgs e)
{
var dataSource = EnumToList<ContainerStatus>();
dropDownList.DataSource = dataSource;
dropDownList.DataValueField = "Key";
dropDownList.DataTextField = "Value";
dropDownList.DataBind();
}