C#之枚举类型作为数据源绑定ComboBox
private void _initComboBoxByEnum<TEnum>(ComboBox cbb,bool isAddNull,string descriptType,string valueType,params string[] removeItem)
{
Type type = typeof(TEnum);
FieldInfo[] fields = type.GetFields();
DataTable dt = new DataTable ();
dt.Columns.Add("Description",Type.GetType(descriptType));
dt.Columns.Add("Value",Type.GetType(valueType));
if(isAddNull)
{
DataRow dw = dt.NewRow();
dw["Description"] = "请选择";
dw["Value"] = -1;
dt.Rows.Add(dw);
}
foreach(Field item in fields)
{
if(removeItem != null && removeItem.Count()>0 && removeItem.Contains(item.Name))
{
continue;
}
if(!item.IsSpecialName)
{
DataRow dw = dt.NewRow();
dw["Description"] = ietm.Name;
dw["Value"] = item.GetRawConstantValue();
dt.Rows.Add(dw);
}
}
cbb.DataSource = dt;
cbb.DisplayMember = "Description";
cbb.ValueMember = "Value";
}