C# 将枚举绑定到WinForms组合框,然后设置它
很多人已经回答了如何在WinForms中将枚举绑定到组合框的问题。它是这样的:C# 将枚举绑定到WinForms组合框,然后设置它,c#,.net,winforms,combobox,enums,C#,.net,Winforms,Combobox,Enums,很多人已经回答了如何在WinForms中将枚举绑定到组合框的问题。它是这样的: comboBox1.DataSource = Enum.GetValues(typeof(MyEnum)); 但是,如果不能设置要显示的实际值,这是非常无用的 我试过: comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null 我也尝试过: comboBox1.SelectedIndex = Con
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
有人知道怎么做吗?试试:
comboBox1.SelectedItem = MyEnum.Something;
编辑:
哎呀,你已经试过了。然而,当我的comboBox被设置为DropDownList时,它对我有效
以下是我的完整代码,适用于我(包括下拉列表和下拉列表):
您可以使用“FindString..”函数:
Public Class Form1
Public Enum Test
pete
jack
fran
bill
End Enum
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = [Enum].GetValues(GetType(Test))
ComboBox1.SelectedIndex = ComboBox1.FindStringExact("jack")
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Test.jack.ToString())
ComboBox1.SelectedIndex = ComboBox1.FindStringExact([Enum].GetName(GetType(Test), Test.jack))
ComboBox1.SelectedItem = Test.bill
End Sub
End Class
应该很好。。。如何判断
SelectedItem
为空?您可以使用KeyValuePair值列表作为组合框的数据源。您需要一个助手方法,在该方法中可以指定枚举类型,并返回IEnumerable>,其中int是枚举的值,string是枚举值的名称。在组合框中,将DisplayMember属性设置为“键”,将ValueMember属性设置为“值”。值和键是KeyValuePair结构的公共属性。然后,当您像现在这样将SelectedItem属性设置为枚举值时,它应该可以工作。目前我使用的是Items属性,而不是数据源,这意味着我必须为每个枚举值调用Add,但它是一个小枚举,而且还是它的临时代码
然后我可以对值执行Convert.ToInt32,并使用SelectedIndex进行设置
暂时的解决方案,但雅格尼现在
为这些想法干杯,在获得一轮客户反馈后,我可能会在制作正确版本时使用它们。代码
comboBox1.SelectedItem = MyEnum.Something;
如果没有问题,问题必须存在于数据绑定中。数据绑定分配发生在构造函数之后,主要是在第一次显示组合框时。尝试在加载事件中设置该值。例如,添加以下代码:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
comboBox1.SelectedItem = MyEnum.Something;
}
然后检查它是否有效。我使用以下帮助器方法,您可以将其绑定到列表
''' <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
“”
''将枚举作为可排序列表返回。
'''
''GetType(某些枚举)
公共共享函数GetEnumAsList(ByVal t作为类型)作为SortedList(字符串,整数)
如果不是伊索菌,那么
抛出新ArgumentException(“类型不是枚举”)
如果结束
作为新分拣列表的Dim项目(字符串,整数)
将枚举值设置为整数()=[Enum].GetValues(t)
Dim enumNames As String()=[Enum].GetNames(t)
对于i,整数=0到enumValues.GetUpperBound(0)
添加(枚举名称(i)、枚举值(i))
下一个
退货项目
端函数
假设您有以下枚举
public enum Numbers {Zero = 0, One, Two};
您需要有一个结构来将这些值映射到字符串:
public struct EntityName
{
public Numbers _num;
public string _caption;
public EntityName(Numbers type, string caption)
{
_num = type;
_caption = caption;
}
public Numbers GetNumber()
{
return _num;
}
public override string ToString()
{
return _caption;
}
}
public object[] GetNumberNameRange()
{
return new object[]
{
new EntityName(Number.Zero, "Zero is chosen"),
new EntityName(Number.One, "One is chosen"),
new EntityName(Number.Two, "Two is chosen")
};
}
现在返回一个对象数组,其中所有枚举映射到一个字符串:
public struct EntityName
{
public Numbers _num;
public string _caption;
public EntityName(Numbers type, string caption)
{
_num = type;
_caption = caption;
}
public Numbers GetNumber()
{
return _num;
}
public override string ToString()
{
return _caption;
}
}
public object[] GetNumberNameRange()
{
return new object[]
{
new EntityName(Number.Zero, "Zero is chosen"),
new EntityName(Number.One, "One is chosen"),
new EntityName(Number.Two, "Two is chosen")
};
}
并使用以下命令填充组合框:
ComboBox numberCB = new ComboBox();
numberCB.Items.AddRange(GetNumberNameRange());
创建一个函数来检索枚举类型,以防将其传递给函数
public Numbers GetConversionType()
{
EntityName type = (EntityName)numberComboBox.SelectedItem;
return type.GetNumber();
}
然后你就可以了:)public Form1()
{
初始化组件();
comboBox.DataSource=EnumWithName.ParseEnum();
comboBox.DisplayMember=“Name”;
}
公共类EnumWithName
{
公共字符串名称{get;set;}
公共T值{get;set;}
公共静态EnumWithName[]ParseEnum()
{
列表=新列表();
foreach(Enum.GetValues(typeof(T))中的对象o)
{
列表。添加(新的EnumWithName
{
Name=Enum.GetName(typeof(T),o).Replace(“”,“”),
值=(T)o
});
}
return list.ToArray();
}
}
公共枚举搜索类型
{
价值1,
价值2
}
这里可能有一个老问题,但我有这个问题,而且解决方法很简单,我发现了这个问题
它利用了数据库,工作得很好,所以请查看它
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
comboBox1.SelectedIndex = (int)MyEnum.Something;
comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something);
这两种方法对我都有效。你确定没有其他问题吗?这就是解决方案
要在组合框中加载枚举项,请执行以下操作:
comboBox1.Items.AddRange( Enum.GetNames(typeof(Border3DStyle)));
然后将枚举项用作文本:
toolStripStatusLabel1.BorderStyle = (Border3DStyle)Enum.Parse(typeof(Border3DStyle),comboBox1.Text);
枚举
public enum Status { Active = 0, Canceled = 3 };
从中设置下拉值
cbStatus.DataSource = Enum.GetValues(typeof(Status));
从选定项获取枚举
Status status;
Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status);
状态;
TryParse(cbStatus.SelectedValue.ToString(),输出状态);
将枚举转换为字符串列表,并将其添加到组合框中
comboBox1.DataSource = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
用于将枚举设置为下拉列表的数据源的通用方法 显示将是名称。 所选值将是枚举本身
public IList<KeyValuePair<string, T>> GetDataSourceFromEnum<T>() where T : struct,IConvertible
{
IList<KeyValuePair<string, T>> list = new BindingList<KeyValuePair<string, T>>();
foreach (string value in Enum.GetNames(typeof(T)))
{
list.Add(new KeyValuePair<string, T>(value, (T)Enum.Parse(typeof(T), value)));
}
return list;
}
public IList GetDataSourceFromEnum()其中T:struct,IConvertible
{
IList list=new BindingList();
foreach(Enum.GetNames(typeof(T))中的字符串值)
{
添加(新的KeyValuePair(value,(T)Enum.Parse(typeof(T),value));
}
退货清单;
}
这一直是个问题。
如果您有一个排序的枚举,例如从0到
public enum Test
one
Two
Three
End
您可以将名称绑定到组合框,而不是使用。SelectedValue
属性使用。SelectedIndex
Combobox.DataSource = System.Enum.GetNames(GetType(test))
和
Dim x as byte = 0
Combobox.Selectedindex=x
试试这个:
// fill list
MyEnumDropDownList.DataSource = Enum.GetValues(typeof(MyEnum));
// binding
MyEnumDropDownList.DataBindings.Add(new Binding("SelectedValue", StoreObject, "StoreObjectMyEnumField"));
StoreObject是我的对象示例,其StoreObjectMyEnumField属性用于存储MyEnum值。公共静态无效FillByEnumOrderByNumber(this System.Windows.Forms.ListControl ctrl,TEnum enum1,bool ShowValueInPlay=true),其中TEnum:struct
public static void FillByEnumOrderByNumber<TEnum>(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select
new
KeyValuePair<TEnum, string>( (enumValue), enumValue.ToString());
ctrl.DataSource = values
.OrderBy(x => x.Key)
.ToList();
ctrl.DisplayMember = "Value";
ctrl.ValueMember = "Key";
ctrl.SelectedValue = enum1;
}
public static void FillByEnumOrderByName<TEnum>(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true ) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select
new
KeyValuePair<TEnum,string> ( (enumValue), enumValue.ToString() );
ctrl.DataSource = values
.OrderBy(x=>x.Value)
.ToList();
ctrl.DisplayMember = "Value";
ctrl.ValueMember = "Key";
ctrl.SelectedValue = enum1;
}
{
如果(!typeof(TEnum).IsEnum)抛出新的ArgumentException(“需要枚举类型。”,“enumObj”);
var values=从Enum.GetValues中的TEnum enumValue开始(typeof(TEnum))
选择
新的
KeyValuePair((enumValue),enumValue.ToString();
ctrl.DataSource=值
.OrderBy(x=>x.Key)
.ToList();
ctrl.DisplayMember=“Value”;
ctrl.ValueMember=“键”;
ctrl.SelectedValue=enum1;
}
public static void FillByEnumOrderByName(this System.Windows.Forms.ListControl ctrl,TEnum enum1,bool showValueInPlay=true),其中TEnum:struct
// fill list
MyEnumDropDownList.DataSource = Enum.GetValues(typeof(MyEnum));
// binding
MyEnumDropDownList.DataBindings.Add(new Binding("SelectedValue", StoreObject, "StoreObjectMyEnumField"));
public static void FillByEnumOrderByNumber<TEnum>(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select
new
KeyValuePair<TEnum, string>( (enumValue), enumValue.ToString());
ctrl.DataSource = values
.OrderBy(x => x.Key)
.ToList();
ctrl.DisplayMember = "Value";
ctrl.ValueMember = "Key";
ctrl.SelectedValue = enum1;
}
public static void FillByEnumOrderByName<TEnum>(this System.Windows.Forms.ListControl ctrl, TEnum enum1, bool showValueInDisplay = true ) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))
select
new
KeyValuePair<TEnum,string> ( (enumValue), enumValue.ToString() );
ctrl.DataSource = values
.OrderBy(x=>x.Value)
.ToList();
ctrl.DisplayMember = "Value";
ctrl.ValueMember = "Key";
ctrl.SelectedValue = enum1;
}
public enum Colors
{
Red = 10,
Blue = 20,
Green = 30,
Yellow = 40,
}
comboBox1.DataSource = Enum.GetValues(typeof(Colors));
cbMultiColumnMode.Properties.Items.AddRange(typeof(MultiColumnMode).GetEnumNames());
MultiColumnMode multiColMode = (MultiColumnMode)cbMultiColumnMode.SelectedIndex;
yourComboBox.DataSource = Enum.GetValues(typeof(YourEnum));
YourEnum enum = (YourEnum) yourComboBox.SelectedItem;
yourComboBox.SelectedItem = YourEnem.Foo;
public enum Status { Active = 0, Canceled = 3 };
cbStatus.DataSource = Enum.GetValues(typeof(Status));
Status? status = cbStatus.SelectedValue as Status?;
if((YouEnum)ComboBoxControl.SelectedItem == YouEnum.Español)
{
//TODO: type you code here
}
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));
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;
public static class ControlExtensions
{
public static void BindToEnum<TEnum>(this ComboBox comboBox)
{
var enumType = typeof(TEnum);
var fields = enumType.GetMembers()
.OfType<FieldInfo>()
.Where(p => p.MemberType == MemberTypes.Field)
.Where(p => p.IsLiteral)
.ToList();
var valuesByName = new Dictionary<string, object>();
foreach (var field in fields)
{
var descriptionAttribute = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
var value = (int)field.GetValue(null);
var description = string.Empty;
if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
{
description = descriptionAttribute.Description;
}
else
{
description = field.Name;
}
valuesByName[description] = value;
}
comboBox.DataSource = valuesByName.ToList();
comboBox.DisplayMember = "Key";
comboBox.ValueMember = "Value";
}
}
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
comboBox1.SelectedIndex = comboBox1.FindStringExact(MyEnum.something.ToString());