将枚举类型绑定到WinForms组合框,然后进行设置

141

很多人已经回答了如何在WinForms中将枚举绑定到组合框的问题。它像这样:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

但是如果不能设置实际值来显示,那就没有多大用处了。

我尝试过:

comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null

我还尝试过:

comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something); // ArgumentOutOfRangeException, SelectedIndex remains -1

有人有任何想法怎么做吗?


3
为什么不尝试使用 ComboBox.SelectedValue 呢? - Oliver Friedrich
6
如果你的问题已经得到回答,你应该选择一个答案。 - Ryan Leach
数据绑定枚举的目的并不是很清楚。枚举在运行时很可能不会改变。您还可以编写一个扩展方法,将组合框的项集合填充为枚举的所有值。 - Andreas
相关链接:https://dev59.com/L2035IYBdhLWcg3wE71s - JYelton
@OliverFriedrich 对我来说,SelectedValue 引发了一个 InvalidOperationException。"无法在具有空 ValueMemberListControl 中设置 SelectedValue。" - Tyler
28个回答

3
这是将枚举类型的项加载到组合框中的解决方案:
comboBox1.Items.AddRange( Enum.GetNames(typeof(Border3DStyle)));

然后将枚举项用作文本:

toolStripStatusLabel1.BorderStyle = (Border3DStyle)Enum.Parse(typeof(Border3DStyle),comboBox1.Text);

2
public Form1()
{
    InitializeComponent();
    comboBox.DataSource = EnumWithName<SearchType>.ParseEnum();
    comboBox.DisplayMember = "Name";
}

public class EnumWithName<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public static EnumWithName<T>[] ParseEnum()
    {
        List<EnumWithName<T>> list = new List<EnumWithName<T>>();

        foreach (object o in Enum.GetValues(typeof(T)))
        {
            list.Add(new EnumWithName<T>
            {
                Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
                Value = (T)o
            });
        }

        return list.ToArray();
    }
}

public enum SearchType
{
    Value_1,
    Value_2
}

在我看来,如果像添加“全部”/“全选”选项到ComboBox以过滤搜索中的所有行这样的功能,可能需要更完整的示例源代码。 - Kiquenet

2

这些方法对我都无效,但这个方法有效(并且它还可以为每个枚举值的名称提供更好的描述)。我不确定是由于.net更新还是其他原因,但无论如何我认为这是最佳方式。你需要添加以下引用:

using System.ComponentModel;

enum MyEnum
{
    [Description("Red Color")]
    Red = 10,
    [Description("Blue Color")]
    Blue = 50
}

....

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

当您想要访问数据时,请使用以下两行:

        Enum.TryParse<MyEnum>(cmbxNewBox.SelectedValue.ToString(), out MyEnum proc);
        int nValue = (int)proc;

1
你可以使用扩展方法。
 public static void EnumForComboBox(this ComboBox comboBox, Type enumType)
 {
     var memInfo = enumType.GetMembers().Where(a => a.MemberType == MemberTypes.Field).ToList();
     comboBox.Items.Clear();
     foreach (var member in memInfo)
     {
         var myAttributes = member.GetCustomAttribute(typeof(DescriptionAttribute), false);
         var description = (DescriptionAttribute)myAttributes;
         if (description != null)
         {
             if (!string.IsNullOrEmpty(description.Description))
             {
                 comboBox.Items.Add(description.Description);
                 comboBox.SelectedIndex = 0;
                 comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
             }
         }   
     }
 }

如何使用... 声明枚举

using System.ComponentModel;

public enum CalculationType
{
    [Desciption("LoaderGroup")]
    LoaderGroup,
    [Description("LadingValue")]
    LadingValue,
    [Description("PerBill")]
    PerBill
}

这个方法在组合框项目中显示描述

combobox1.EnumForComboBox(typeof(CalculationType));

1
将枚举转换为字符串列表,并将其添加到组合框中。
comboBox1.DataSource = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();

使用selectedItem设置显示的值

comboBox1.SelectedItem = SomeEnum.SomeValue;

1
我使用以下的辅助方法,你可以将其绑定到你的列表上。
    ''' <summary>
    ''' Returns enumeration as a sortable list.
    ''' </summary>
    ''' <param name="t">GetType(some enumeration)</param>
    Public Shared Function GetEnumAsList(ByVal t As Type) As SortedList(Of String, Integer)

        If Not t.IsEnum Then
            Throw New ArgumentException("Type is not an enumeration.")
        End If

        Dim items As New SortedList(Of String, Integer)
        Dim enumValues As Integer() = [Enum].GetValues(t)
        Dim enumNames As String() = [Enum].GetNames(t)

        For i As Integer = 0 To enumValues.GetUpperBound(0)
            items.Add(enumNames(i), enumValues(i))
        Next

        Return items

    End Function

1
    public enum Colors
    {
        Red = 10,
        Blue = 20,
        Green = 30,
        Yellow = 40,
    }

comboBox1.DataSource = Enum.GetValues(typeof(Colors));

完整源代码...将枚举绑定到Combobox


0
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

comboBox1.SelectedIndex = (int)MyEnum.Something;

comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something);

这两个对我都有效,你确定没有其他问题吗?


2
不确定在使用自定义枚举值时是否会起作用,例如 enum MyEnum { Something = 47 } - Samantha Branham

0

只使用这种方式进行强制类型转换:

if((YouEnum)ComboBoxControl.SelectedItem == YouEnum.Español)
{
   //TODO: type you code here
}

0
在 Framework 4 中,您可以使用以下代码:
例如,将 MultiColumnMode 枚举绑定到组合框:
cbMultiColumnMode.Properties.Items.AddRange(typeof(MultiColumnMode).GetEnumNames());

获取选定的索引:

MultiColumnMode multiColMode = (MultiColumnMode)cbMultiColumnMode.SelectedIndex;

注意:在此示例中,我使用DevExpress组合框,您可以在Win Form组合框中执行相同的操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接