在组合框显示枚举用空格 [英] Display enum in ComboBox with spaces
问题描述
我有一个枚举,例如:
enum MyEnum
{
My_Value_1,
My_Value_2
}
使用:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
但现在我的问题:我如何替换_和,使之成为
项用空格代替下划线?和数据绑定对象仍然
作品
But now my question: How can I replace the "_" with " " so that it becomes items with spaces instead of underscores? And that a databound object still works
推荐答案
如果您有机会获得Framework 3.5中,你可以这样做这样的:
If you have access to the Framework 3.5, you could do something like this:
Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(e=> new
{
Value = e,
Text = e.ToString().Replace("_", " ")
});
这将返回一个匿名类型的IEnumerable,包含的值属性,那就是枚举类型本身,而文本的属性,将包含与空间取代了下划线枚举的字符串表示。
This will return you an IEnumerable of an anonymous type, that contains a Value property, that is the enumeration type itself, and a Text property, that will contain the string representation of the enumerator with the underscores replaced with space.
Value属性的目的是,你可以确切地知道被选为该枚举的组合,而无需获得下划线背部和解析字符串。
The purpose of the Value property is that you can know exactly which enumerator was chosen in the combo, without having to get the underscores back and parse the string.
这篇关于在组合框显示枚举用空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!