如何将枚举粘贴到 .Net WinForm ComboBox 中
假设我有几个代表......例如数据库供应商的枚举:Unknown
、Oracle
、Sybase
、SQL Server 2005
、SQL Server 2008
等。我想让用户在所有这些之间进行选择,但不能从组合框中选择 Unknown
。当用户选择枚举时,他们应该看到人类可读的描述(希望来自属性)。但是,选择的实际对象应该是该特定类型的枚举。
这可以在额外字典的帮助下手动组合在一起,但我不想这样做,而是使用惯用且最干净的方式。
您能否分享一个代码示例,或者至少一个好的链接?
PS 有没有一种简单的方法来获取类型供应商的所有枚举的集合,除了 Unknown
(它将有一个 0
的短/int值,如规定的那样)比尔·瓦格纳)?
Suppose I have several enums representing ... for example database vendors: Unknown
, Oracle
, Sybase
, SQL Server 2005
, SQL Server 2008
, etc. I want to let the user select between all of these but an Unknown
from a Combo Box. When the user selects an enum, they should see a human-readable description (which would hopefully come from an attribute). However, the actual object selected should be an enum of that specific type.
This can be hacked together manually with the help of extra dictionary, but I do not want to do that, and rather use an idiomatic and the cleanest way possible.
Would you kindly share a code sample, or at least a good link?
P.S. Is there an easy way to grab a collection of all enums of the type vendor, except for Unknown
(which will have a short/int value of 0
, as prescribed by Bill Wagner)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要将友好名称与值关联起来,您可以使用
DescriptionAttribute
,如 这个答案。处理ComboBox
的Format
事件以显示说明:注意:如果您的应用程序需要可本地化,则
Description
属性可能不是最好的选择。相反,您可以使用名称如DisplayName_DbVendor_Oracle
、DisplayName_DbVendor_SqlServer
等的字符串资源。然后,您可以检索值的显示名称,如下所示:编辑:如果需要排序按描述的值,只需更改 LINQ 查询,如下所示:
To associate a friendly name to the values, you can use
DescriptionAttribute
, as shown in this answer. Handle theFormat
event of theComboBox
to display the description:Note: if your application needs to be localizable, the
Description
attribute is probably not the best option. Instead, you could use string resources with names likeDisplayName_DbVendor_Oracle
,DisplayName_DbVendor_SqlServer
, etc. You can then retrieve the display name for a value as follows:EDIT: if you need to sort the values by description, just change the LINQ query as follows: