【问题标题】:How do i show enum values in a combo-box?如何在组合框中显示枚举值?
【发布时间】:2011-07-01 05:02:51
【问题描述】:

如何在组合框中显示枚举值?下面的代码导致组合框的所有显示名称都是“caseHandler.cState”。我希望它具有枚举值的实际名称。

我的枚举定义如下:

public enum caseState
{
    Active = 1,
    Finished,
    Problem
}

我有一个这样定义的类:

public class cState
{    
    public string _name;
    public int _id;

    public cState(int id,string name)
    {
        _name = name;
        _id = id;
    }
}

以及用于填充我的组合框的代码:

ArrayList AL = new ArrayList();

foreach (string cs in Enum.GetNames(typeof(caseState)))
{
    cState aEnum = new cState((int)Enum.Parse(typeof(caseState),cs),cs);
    AL.Add(aEnum);
}


cbState.DisplayMember = "_name";
cbState.ValueMember = "_id";

cbState.DataSource = AL;

【问题讨论】:

标签: c# winforms enums combobox


【解决方案1】:

你试过用吗

cbState.DataSource = Enum.GetNames(typeof(caseState));

当检索数据时,只需解析它

【讨论】:

  • @Stecya - 这行得通。但是你能解释一下为什么我写的代码不起作用吗?
  • @Stecya - 好的,我发现了错误。我应该将 _name 和 _id 实现为属性,然后它会起作用。
【解决方案2】:

Here My Code ,你可以同时拥有文本和值并填充 Combobox

 public enum LayerType : int
{

    [Description("محوطه")]
    Area = 1,


    [Description("ساختمان")]
    Building = 2,


    [Description("بارانداز")]
    Wharf = 3,}

drpLayer.DataSource = Enum.GetValues(typeof(LayerType))
             .Cast<Enum>()
             .Select(value => new
        {
        (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
        value
         })
        .OrderBy(item => item.value)
        .ToList();
            drpLayer.DisplayMember = "Description";
            drpLayer.ValueMember = "value";

【讨论】:

    猜你喜欢
    • 2015-08-03
    • 2012-03-03
    • 1970-01-01
    • 2021-11-30
    • 2011-04-17
    • 1970-01-01
    • 2014-10-04
    • 2018-09-17
    • 2012-08-19
    相关资源
    最近更新 更多