将枚举绑定到 WinForms 组合框,然后设置它
很多人已经回答了如何在 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
有谁知道如何做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
枚举
设置下拉值 从
所选项目获取枚举
The Enum
Setting the drop down values from it
Getting the enum from the selected item
为了简化:
首先初始化此命令:(例如在
InitalizeComponent()
之后)检索组合框中选定的项目:
如果要为组合框设置值:
To simplify:
First Initialize this command: (e.g. after
InitalizeComponent()
)To retrieve selected item on combobox:
If you want to set value for the combobox:
代码
没问题,问题一定出在DataBinding上。 DataBinding 赋值发生在构造函数之后,主要是在第一次显示组合框时。 尝试在 Load 事件中设置该值。 例如,添加以下代码:
并检查它是否有效。
The code
is ok, the problem must reside in the DataBinding. DataBinding assignments occur after the constructor, mainly the first time the combobox is shown. Try to set the value in the Load event. For example, add this code:
And check if it works.
尝试:
编辑:
哎呀,你已经尝试过了。 但是,当我的组合框设置为 DropDownList 时,它对我有用。
这是适合我的完整代码(同时包含 DropDown 和 DropDownList):
Try:
EDITS:
Whoops, you've tried that already. However, it worked for me when my comboBox was set to be a DropDownList.
Here is my full code which works for me (with both DropDown and DropDownList):
假设您有以下枚举,
您需要一个结构体来将这些值映射到字符串:
现在返回一个对象数组,其中所有枚举都映射到字符串:
并使用以下内容填充组合框:
创建一个函数来检索枚举类型以防万一您想将其传递给函数
,然后就可以了:)
Let's say you have the following enum
You need to have a struct to map those values to a string:
Now return an array of objects with all the enums mapped to a string:
And use the following to populate your combo box:
Create a function to retrieve the enum type just in case you want to pass it to a function
and then you should be ok :)
这可能永远不会在所有其他响应中看到,但这是我想出的代码,这样做的好处是使用
DescriptionAttribute
(如果存在),但否则使用枚举值本身。我使用字典是因为它有一个现成的键/值项模式。
List>
也可以工作,并且没有不必要的散列,但字典可以使代码更清晰。我得到的成员的
MemberType
为Field
并且是文字。 这将创建一个仅包含枚举值成员的序列。 这是很强大的,因为枚举不能有其他字段。This is probably never going to be seen among all the other responses, but this is the code I came up with, this has the benefit of using the
DescriptionAttribute
if it exists, but otherwise using the name of the enum value itself.I used a dictionary because it has a ready made key/value item pattern. A
List<KeyValuePair<string,object>>
would also work and without the unnecessary hashing, but a dictionary makes for cleaner code.I get members that have a
MemberType
ofField
and that are literal. This creates a sequence of only members that are enum values. This is robust since an enum cannot have other fields.试试这个:
StoreObject 是我的对象示例,其中 StoreObjectMyEnumField 属性用于存储 MyEnum 值。
Try this:
StoreObject is my object example with StoreObjectMyEnumField property for store MyEnum value.
这对我有用:
This worked for me:
这就是解决方案
在组合框中加载枚举项:
然后使用枚举项作为文本:
this is the solution
to load item of enum in combobox :
And then use the enum item as text :
根据 @Amir Shenouda 的回答,我最终得到以下结果:
枚举的定义:
从中设置下拉值:
从所选项目中获取枚举:
Based on the answer from @Amir Shenouda I end up with this:
Enum's definition:
Setting the drop down values from it:
Getting the enum from the selected item:
这些都不适合我,但这个确实有用(而且它还有一个额外的好处,那就是能够对每个枚举的名称有更好的描述)。 我不确定这是否是由于 .net 更新所致,但无论如何我认为这是最好的方法。 您需要添加对以下内容的引用:
using System.ComponentModel;
然后当你想访问数据时使用这两行:
None of these worked for me, but this did (and it had the added benefit of being able to have a better description for the name of each enum). I'm not sure if it's due to .net updates or not, but regardless I think this is the best way. You'll need to add a reference to:
using System.ComponentModel;
Then when you want to access the data use these two lines:
我使用以下辅助方法,您可以将其绑定到您的列表。
I use the following helper method, which you can bind to your list.
将枚举转换为字符串列表并将其添加到组合框
使用 selectedItem 设置显示值
Convert the enum to a list of string and add this to the comboBox
Set the displayed value using selectedItem
完整源代码...将枚举绑定到组合框
Full Source...Binding an enum to Combobox
您可以使用扩展方法
如何使用...
声明枚举
此方法在组合框项目中显示描述
You can use a extension method
How to use ...
Declare enum
This method show description in Combo box items
应该可以正常工作...你怎么知道
SelectedItem
为空?should work just fine ... How can you tell that
SelectedItem
is null?您可以使用“FindString..”函数:
You could use the "FindString.." functions:
您可以使用 KeyValuePair 值列表作为组合框的数据源。 您将需要一个辅助方法,您可以在其中指定枚举类型并返回 IEnumerable> 其中 int 是枚举值,string 是枚举值的名称。 在组合框中,将 DisplayMember 属性设置为“Key”,将 ValueMember 属性设置为“Value”。 Value 和 Key 是 KeyValuePair 结构的公共属性。 然后,当您像您所做的那样将 SelectedItem 属性设置为枚举值时,它应该可以工作。
You can use a list of KeyValuePair values as the datasource for the combobox. You will need a helper method where you can specify the enum type and it returns IEnumerable> where int is the value of enum and string is the name of the enum value. In your combobox, set, DisplayMember property to 'Key' and ValueMember property to 'Value'. Value and Key are public properties of KeyValuePair structure. Then when you set SelectedItem property to an enum value like you are doing, it should work.
目前我使用的是 Items 属性而不是 DataSource,这意味着我必须为每个枚举值调用 Add,但它是一个小枚举,而且无论如何都是临时代码。
然后我可以对值执行 Convert.ToInt32 并使用 SelectedIndex 设置它。
临时解决方案,但目前是 YAGNI。
为这些想法干杯,当我在收到一轮客户反馈后制作正确的版本时,我可能会使用它们。
At the moment I am using the Items property rather than the DataSource, it means I have to call Add for each enum value, but its a small enum, and its temporary code anyway.
Then I can just do the Convert.ToInt32 on the value and set it with SelectedIndex.
Temporary solution, but YAGNI for now.
Cheers for the ideas, I will probably use them when I do the proper version after getting a round of customer feedback.
也许是老问题,但我遇到了问题,解决方案很简单,我发现这个 http://www.c-sharpcorner.com/UploadFile/mahesh/1220/
它利用了数据绑定并且工作得很好,所以请检查一下。
Old question perhaps here but I had the issue and the solution was easy and simple, I found this http://www.c-sharpcorner.com/UploadFile/mahesh/1220/
It makes use of the databining and works nicely so check it out.
这两个都对我有用,你确定没有其他问题吗?
Both of these work for me are you sure there isn't something else wrong?
将枚举设置为下拉列表
显示数据源的通用方法是名称。
选定的值将是 Enum 本身
Generic method for setting a enum as datasource for drop downs
Display would be name.
Selected value would be Enum itself
这一直是个问题。
如果您有一个排序枚举,例如从 0 到 ...,
您可以将名称绑定到组合框,而不是使用
.SelectedValue
属性,而是使用.SelectedIndex
和
That was always a problem.
if you have a Sorted Enum, like from 0 to ...
you can bind names to combobox and instead of using
.SelectedValue
property use.SelectedIndex
and the
在 Framework 4 中,您可以使用以下代码:
将 MultiColumnMode 枚举绑定到组合框,例如:
并获取所选索引:
注意:在本例中我使用 DevExpress 组合框,您可以在 Win Form 组合框中执行相同操作
In Framework 4 you can use the following code:
To bind MultiColumnMode enum to combobox for example:
and to get selected index:
note: I use DevExpress combobox in this example, you can do the same in Win Form Combobox
这次聚会有点晚了,
SelectedValue.ToString() 方法应该引入 DisplayedName。
然而这篇文章DataBinding Enum 以及描述展示了一种方便的方法,不仅可以实现这一点,而且您还可以向枚举添加自定义描述属性,并根据需要将其用于显示的值。 非常简单和容易,大约 15 行左右的代码(除非你算上花括号)。
这是非常漂亮的代码,您可以将其作为启动的扩展方法......
A little late to this party ,
The SelectedValue.ToString() method should pull in the DisplayedName .
However this article DataBinding Enum and also With Descriptions shows a handy way to not only have that but instead you can add a custom description attribute to the enum and use it for your displayed value if you preferred. Very simple and easy and about 15 lines or so of code (unless you count the curly braces) for everything.
It is pretty nifty code and you can make it an extension method to boot ...
仅使用这种方式进行转换:
only use casting this way: