绑定枚举类型(反射)
public static void ItemListBind<T>(CheckBoxList CBTarget) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
//绑定数据
foreach (int myCode in Enum.GetValues(typeof(T)))
{
string myName = Enum.GetName(typeof(T), myCode);
string myValue = myCode.ToString();
ListItem myLi = new ListItem(myName, myValue);
CBTarget.Items.Add(myLi);
}
}
2、类:
public static class EnumManager<TEnum>
{
private static DataTable GetDataTable()
{
Type enumType = typeof(TEnum); // 获取类型对象
FieldInfo[] enumFields = enumType.GetFields();
DataTable table = new DataTable();
table.Columns.Add("Name", Type.GetType("System.String"));
table.Columns.Add("Value", Type.GetType("System.Int32"));
//遍历集合
foreach (FieldInfo field in enumFields)
{
if (!field.IsSpecialName)
{
DataRow row = table.NewRow();
row[0] = field.Name;
row[1] = Convert.ToInt32(field.GetRawConstantValue());
//row[1] = (int)Enum.Parse(enumType, field.Name); 也可以这样
table.Rows.Add(row);
}
}
return table;
}
public static void SetListControl(ListControl list)
{
list.DataSource = GetDataTable();
list.DataTextField = "Name";
list.DataValueField = "Value";
list.DataBind();
}
}
用例:
enum StarList
{
星级 = 0,
星1 = 1,
星2 = 2,
星3 = 3,
星4 = 4,
星5 = 5
}
EnumManager<FeeList>.SetListControl((ListControl)ddl);
转载请注明出处:http://blog.csdn.net/dasihg/article/details/6775450