将枚举绑定到 WinForms 组合框,然后对其进行设置 [英] Binding an enum to a WinForms combo box, and then setting it
本文介绍了将枚举绑定到 WinForms 组合框,然后对其进行设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很多人已经回答了如何在WinForms中将枚举绑定到组合框的问题.是这样的:
a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
但是如果无法设置要显示的实际值,那将毫无用处.
But that is pretty useless without being able to set the actual value to display.
我试过了:
comboBox1.SelectedItem = MyEnum.Something; // Does not work. SelectedItem remains null
我也试过:
comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something); // ArgumentOutOfRangeException, SelectedIndex remains -1
有人知道如何做到这一点吗?
Does anyone have any ideas how to do this?
推荐答案
The Enum
public enum Status { Active = 0, Canceled = 3 };
从中设置下拉值
cbStatus.DataSource = Enum.GetValues(typeof(Status));
从所选项目中获取枚举
Status status;
Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status);
这篇关于将枚举绑定到 WinForms 组合框,然后对其进行设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文