Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将枚举绑定到combobox_C#_Winforms - Fatal编程技术网

C# 如何将枚举绑定到combobox

C# 如何将枚举绑定到combobox,c#,winforms,C#,Winforms,我将使用combobox控件绑定枚举的值 我编写了以下代码: cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum)) .Cast<MyEnum>() .Select(p => new { Key = (int)p, Value = p.ToString() }) .ToList(); myComboBox.DisplayMember = "Value"; myComboBo

我将使用combobox控件绑定枚举的值

我编写了以下代码:

cboPriorLogicalOperator.DataSource = Enum.GetValues(typeof(MyEnum))
    .Cast<MyEnum>()
    .Select(p => new { Key = (int)p, Value = p.ToString() })
    .ToList();

myComboBox.DisplayMember = "Value";
myComboBox.ValueMember = "Key";
cboPriorLogicalOperator.DataSource=Enum.GetValues(typeof(MyEnum))
.Cast()
.Select(p=>new{Key=(int)p,Value=p.ToString()})
.ToList();
myComboBox.DisplayMember=“值”;
myComboBox.ValueMember=“Key”;

它工作得很好,但我想知道是否有更简单的方法。

我认为您的代码很漂亮

唯一的改进是将代码放在扩展方法中

编辑:

仔细想想,您要做的是使用定义中的
Enum
,而不是扩展方法所需的Enum实例

我发现了这个,很好地解决了这个问题:

public class SelectList
{
    // Normal SelectList properties/methods go here

    public static SelectList Of<T>()
    {
       Type t = typeof(T);
       if (t.IsEnum)
       {
           var values = from Enum e in Enum.GetValues(t)
                        select new { ID = e, Name = e.ToString() };
           return new SelectList(values, "Id", "Name");
       }
       return null;
    }
}

// called with 
var list = SelectList.Of<Things>();
或者这个版本,其中键是
int

public class EnumList
{
    public static IEnumerable<KeyValuePair<int, string>> Of<T>()
    {
        return Enum.GetValues(typeof (T))
            .Cast<T>()
            .Select(p => new KeyValuePair<int, string>(Convert.ToInt32(p), p.ToString()))
            .ToList();
    }
}
公共类枚举列表
{
公共静态IEnumerable Of()
{
返回Enum.GetValues(typeof(T))
.Cast()
.Select(p=>newkeyvaluepair(Convert.ToInt32(p),p.ToString())
.ToList();
}
}
为什么不使用:

myComboBox.DataSource  = Enum.GetValues(typeof(MyEnum))

我最近遇到一个问题,我有一个可为空的枚举属性,需要将它绑定到一个组合框。以下是我提出的解决方案:

using System;
using System.Collections.Generic;

namespace ActivitySchedule.Model
{
    public class NullableEnum<T> where T : struct, IComparable
    {
        public string Display { get; private set; }

        public T? Value { get; private set; }

        public static implicit operator T?(NullableEnum<T> o)
        {
            return o.Value;
        }

        public static implicit operator NullableEnum<T>(T? o)
        {
            return new NullableEnum<T>
            {
                Display = o?.ToString() ?? "NA",
                Value = o
            };
        }

        private NullableEnum() { }

        public static IEnumerable<NullableEnum<T>> GetList()
        {
            var items = new List<NullableEnum<T>>
            {
                new NullableEnum<T>
                {
                    Display = "NA",
                    Value = null
                }
            };

            var values = Enum.GetValues(typeof(T));

            foreach (T v in values)
            {
                items.Add(v);
            }

            return items;
        }
    }
}
使用系统;
使用System.Collections.Generic;
命名空间ActivitySchedule.Model
{
公共类NullableEnum,其中T:struct,IComparable
{
公共字符串显示{get;private set;}
公共T?值{get;private set;}
公共静态隐式运算符T?(NullableEnum o)
{
返回o.值;
}
公共静态隐式运算符NullableEnum(T?o)
{
返回新的NullableEnum
{
Display=o?.ToString()??“NA”,
值=o
};
}
私有NullableEnum(){}
公共静态IEnumerable GetList()
{
var items=新列表
{
新的NullableEnum
{
Display=“NA”,
值=空
}
};
var values=Enum.GetValues(typeof(T));
foreach(T v值)
{
增加(五)项;
}
退货项目;
}
}
}
我将对象包装在控制器类中,并更改属性的类型,如下所示:

private MyClass myClass;

public NullableEnum<MyEnum> MyEnum
{
    get { return this.myClass.MyEnum; }
    set { this.myClass.MyEnum = value.Value; }
}
私有MyClass MyClass;
公共NullableEnum MyEnum
{
获取{返回this.myClass.MyEnum;}
设置{this.myClass.MyEnum=value.value;}
}
(它也可以是派生类并重写属性)

我就是这样使用它的:

var types = NullableEnum<MyEnum>.GetList();
this.comboBox1.DataSource = types;
this.comboBox1.DisplayMember = "Display";
this.comboBox1.ValueMember = "Value";
this.comboBox1.Bindings.Add("SelectedValue", myClassController, "MyEnum");
var types=NullableEnum.GetList();
this.comboBox1.DataSource=类型;
this.comboBox1.DisplayMember=“Display”;
this.comboBox1.ValueMember=“Value”;
Add(“SelectedValue”,myClassController,MyEnum”);
私有作废表单1\u加载(对象发送方,事件参数e)
{
comboBox1.DataSource=Enum.GetValues(typeof(Gender));
数组gen=Enum.GetValues(typeof(Gender));
List lstgender=新列表();
foreach(性别g,一般情况下)
添加(新的KeyValuePair(g.ToString(),((char)g));
comboBox1.DataSource=lstgender;
comboBox1.DisplayMember=“key”;
comboBox1.ValueMember=“值”
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
Show(comboBox1.SelectedValue.ToString());
}
公立班学生
{
公共字符串stud_name{get;set;}
公共性别研究{get;set;}
}
公共枚举性别
{
男class='M',
雌性='F'
}

我同意。我们已经将winforms组合框扩展到我们自己的版本中,并在其上有一个BindToEnum方法,该方法非常有效。它看起来也很像这段代码。啊,他们在最初的示例中忽略了这一点。在您的情况下,它将返回
字典
,我想。我添加了一些您应该能够使用的真实代码。我使用了一个
IEnumerable
,因为当我使用enum
HttpStatusCode
进行测试时,我遇到了关键的重复问题,这让我选择了这一个而不是
字典。如果你的解决方案有效,你为什么要寻找一个更简单的解决方案?@Ramhound:我认为可能有一个直接的方法。我确实理解我的代码,但不是每个人都能简单地做到这一点。所以我找了一个更简单的方法。@Homam我不知道您是否有意这样做,但当我为自己的解决方案模仿您的代码时,我必须反转select语句中的键和值类型,以便在组合框中正确显示值。您的方法最终在组合框中显示键。问题的+1实际上提供了答案@gonzobrains修复了它。因为它不绑定键/值对。要从组合框中获取值,必须将SelectedItem强制转换为枚举。请参阅备注部分。我认为,如果我们想在检索到的数据中设置条件,所讨论的代码非常好……否则,您的代码会更好。。
private MyClass myClass;

public NullableEnum<MyEnum> MyEnum
{
    get { return this.myClass.MyEnum; }
    set { this.myClass.MyEnum = value.Value; }
}
var types = NullableEnum<MyEnum>.GetList();
this.comboBox1.DataSource = types;
this.comboBox1.DisplayMember = "Display";
this.comboBox1.ValueMember = "Value";
this.comboBox1.Bindings.Add("SelectedValue", myClassController, "MyEnum");
private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DataSource = Enum.GetValues( typeof(Gender));
    Array gen = Enum.GetValues(typeof(Gender));
    List<KeyValuePair<string, char>> lstgender = new List<KeyValuePair<string,char>>();
    foreach(Gender g in gen)
        lstgender.Add(new KeyValuePair<string,char>(g.ToString(),((char)g)));
    comboBox1.DataSource = lstgender;
    comboBox1.DisplayMember = "key";
    comboBox1.ValueMember = "value"
}

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(comboBox1.SelectedValue.ToString());
}

public class Student
{
    public string stud_name { get; set; }
    public Gender stud_gen { get; set; }
}

public enum Gender
{
    Male='M',
    Female='F'
}