简体   繁体   中英

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

I am binding a Dictionary to a ComboBox which keeps the Enum values.

To retrieve the selected value I used:
comboBox1.SelectedItem which returns a dimensional value of [0,Permanent] .

I just want to retrieve Permanent and then convert it back to 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>

You can access your enum value by casting SelectedItem and accessing Value property.

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 .

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

See this -- 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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