繁体   English   中英

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

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

我将字典绑定到保留枚举值的 ComboBox。

要检索我使用的选定值:
comboBox1.SelectedItem返回[0,Permanent]的维度值。

我只想检索Permanent ,然后将其转换回 Enum。

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

我怎样才能做到这一点?

任何一个:

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

要么:

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

如果组合框的项目源是字典,则 SelectedItem 的类型为:KeyValuePair<[key 类型], JobType>

您可以通过转换 SelectedItem 和访问 Value 属性来访问您的枚举值。

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

我认为这可以解决问题:

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

首先,使用逗号和方括号拆分字符串,并使用该方法删除所有空元素。 这应该为您留下一个包含数字和文本的数组。 使用文本部分进行枚举解析。

请注意,您需要将枚举的Type对象传递给Parse方法,然后您需要转换结果,因为Parse的返回类型是object

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

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

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

数据绑定:

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

我有同样的问题 - (WPF) 我的组合包含键值对中的枚举。

我可以得到枚举的唯一方法是

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

希望这对某人有帮助。 无法相信这如此困难

暂无
暂无

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

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