我有一个枚举示例:
enum MyEnum
{
My_Value_1,
My_Value_2
}通过以下方式:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));但现在我的问题是:如何将"_“替换为”“,使其成为带有空格而不是下划线的项?并且数据绑定对象仍然有效
发布于 2009-07-09 06:09:44
如果您有权访问Framework3.5,则可以执行以下操作:
Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(e=> new
{
Value = e,
Text = e.ToString().Replace("_", " ")
});这将返回一个匿名类型的文本,其中包含一个IEnumerable属性和一个Text属性,前者是枚举类型本身,后者包含枚举数的字符串表示形式,但下划线被替换为空格。
Value属性的用途是,您可以确切地知道在组合框中选择了哪个枚举数,而不必取回下划线并分析字符串。
发布于 2009-07-09 07:10:02
如果您能够修改定义枚举的代码,以便可以在不修改实际枚举值的情况下向值添加属性,则可以使用此扩展方法。
/// <summary>
/// Retrieve the description of the enum, e.g.
/// [Description("Bright Pink")]
/// BrightPink = 2,
/// </summary>
/// <param name="value"></param>
/// <returns>The friendly description of the enum.</returns>
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
MemberInfo[] memInfo = type.GetMember(value.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return value.ToString();
}发布于 2011-06-30 22:55:52
试试这个。
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Select(e => new { Value = e, Description = e.ToString().Replace("_"," ") })
.ToList();
comboBox1.DisplayMember = "Description";
comboBox1.ValueMember = "Value";描述,我更倾向于使用“...although”属性(根据Steve Crane的回答)。
https://stackoverflow.com/questions/1102022
复制相似问题