如何使用值和文本绑定枚举并包含一些带有文本的空格
问题描述:
public enum States
{
[Description("New Mexico")]
NewMexico = 1,
[Description("New York")]
NewYork = 2,
[Description("South Carolina")]
SouthCarolina = 3
}
我能够绑定它,但只能在值和文本中绑定文字正在显示。
所以我必须绑定文本和值两者,但文本应该包含空格,如新墨西哥
I am able to bind this but in value and in text only text is showing.
So i have to bind text and value both but text should contain space like "New Mexico"
答
请看这里:用于枚举元素的人类可读字符串 [ ^ ]
public static List<ListItem> LoadListForListControls<T>()
{
var type = typeof(T);
var list = new List<ListItem>();
foreach (var value in Enum.GetValues(type))
{
var enumValue = (Int32)value;
var fi = value.GetType().GetField(value.ToString());
var customAttributes =
fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
DescriptionAttribute attribute = null;
if (customAttributes.Length > 0)
attribute = (DescriptionAttribute)customAttributes[0];
var item = new ListItem
{
Text = attribute != null
? attribute.Description
: Enum.GetName(type, enumValue),
Value = (Convert.ToInt32(enumValue)).ToString()
};
list.Add(item);
}
return list;
}