简体   繁体   English

C# 如何从 WinForms 中的 ComboBox 获取枚举值?

[英]C# How to get the Enum value from ComboBox in WinForms?

I am binding a Dictionary to a ComboBox which keeps the Enum values.我将字典绑定到保留枚举值的 ComboBox。

To retrieve the selected value I used:要检索我使用的选定值:
comboBox1.SelectedItem which returns a dimensional value of [0,Permanent] . comboBox1.SelectedItem返回[0,Permanent]的维度值。

I just want to retrieve Permanent and then convert it back to Enum.我只想检索Permanent ,然后将其转换回 Enum。

Something like:就像是:
Employee.JobType = Enum.Parse(JobType, comboBox1.SelectedItem)

How can I achieve this?我怎样才能做到这一点?

Either:任何一个:

Employee.JobType = (JobType)Enum.Parse(typeof(JobType), comboBox1.SelectedValue);

Or:要么:

Employee.JobType = (JobType)Enum.Parse(typeof(JobType), comboBox1.SelectedText);

If items source for combo box is a dictionary, SelectedItem is of type: KeyValuePair<[type of key], JobType>如果组合框的项目源是字典,则 SelectedItem 的类型为:KeyValuePair<[key 类型], JobType>

You can access your enum value by casting SelectedItem and accessing Value property.您可以通过转换 SelectedItem 和访问 Value 属性来访问您的枚举值。

var selectedItem = (KeyValuePair<[type of key], JobType>) comboBox1.SelectedItem;
var jobType = selectedItem.Value;

This would do the trick, I think:我认为这可以解决问题:

string[] parts = comboBox1.SelectedItem.Split(
                      new char[] { ',', '[', ']' }, 
                      StringSplitOptions.RemoveEmptyEntries);
Employee.JobType = (JobType)Enum.Parse(typeof(JobType), parts[1].Trim()));

First, split up the string using comma and the square brackets, and have the method remove any empty elements.首先,使用逗号和方括号拆分字符串,并使用该方法删除所有空元素。 This should leave you with an array containing the number and the text.这应该为您留下一个包含数字和文本的数组。 Use the text part for enum parsing.使用文本部分进行枚举解析。

Note that you need to pass the Type object for the enum into the Parse method, and then you need to cast the result, since the return type of Parse is object .请注意,您需要将枚举的Type对象传递给Parse方法,然后您需要转换结果,因为Parse的返回类型是object

Employee.JobType = (JobTypeEnum)Enum.Parse(typeof(JobTypeEnum), comboBox1.SelectedValue);

See this -- http://www.fmsinc.com/free/NewTips/NET/NETtip4.asp看这个——http://www.fmsinc.com/free/NewTips/NET/NETtip4.asp

PeopleNames people = (PeopleNames)Enum.Parse(ComboBox1.SelectedValue, PeopleNames)

Data Binding:数据绑定:

ComboBox1.DataSource = System.Enum.GetValues(typeof(PeopleNames))

I had the same problem - (WPF) where my combo contained an enumeration in keyvalue pairs.我有同样的问题 - (WPF) 我的组合包含键值对中的枚举。

The ONLY way I could get the enumeration out was by我可以得到枚举的唯一方法是

 KeyValuePair<string,string> selectedPair =  (KeyValuePair<string,string>)(cmbApplications.SelectedItem);
 ProTraceLicence.Products chosenProduct = (ProTraceLicence.Products)Enum.Parse(typeof(ProTraceLicence.Products), selectedPair.Key);

Hope this helps someone.希望这对某人有帮助。 Can't believe it's so difficult无法相信这如此困难

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM