如何使用值和文本绑定枚举并包含一些带有文本的空格 [英] How to bind enum with value and text and contain some space with text
本文介绍了如何使用值和文本绑定枚举并包含一些带有文本的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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;
}
这篇关于如何使用值和文本绑定枚举并包含一些带有文本的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文