添加枚举组合框 [英] Adding enum to combobox
问题描述
嗨我可以知道如何让下面的枚举值绑定到组合框?
我写了下面的代码效果很好,但不知道这是最好的方法。
Hi may i know how to get the enum value below to bind into the combobox? I wrote the below code which works well but wonder is this the best way.
public enum CourseStudentStatus
{
Active = 1,
Completed = 2,
TempStopped = 3,
Stopped = 4,
}
//Bind Course Status
Dictionary<string, int> list = new Dictionary<string, int>();
foreach (int enumValue in Enum.GetValues(typeof(CourseStudentStatus)))
list.Add(Enum.GetName(typeof(CourseStudentStatus), enumValue), enumValue);
var column = ((DataGridViewComboBoxColumn)dgv.Columns["studentCourseStatus"]);
column.DataPropertyName = "StudentStatus";
column.DisplayMember = "Key";
column.ValueMember = "Value";
column.DataSource= list.ToList();
-----------------更新------------------- 结果
您好我有根据Sanjeevakumar Hiremat改变了我的代码,这和它完美的作品。
----------------- UPDATE -------------------
Hi i have changed my code to this according to Sanjeevakumar Hiremat and it works perfectly.
cbStatus.DataSource = Enum.GetValues(typeof运算(CourseStudentStatus));
然而,当我想一个get()和想要的值绑定回cbStatus,将其转换错误{未将对象引用设置到对象的实例。}结果
cbStatus.SelectedValue = Course.Status;
However, when i want to a Get() and want to bind the value back to the cbStatus, it cast error {"Object reference not set to an instance of an object."}
cbStatus.SelectedValue = Course.Status;
.
cbStatus.Datasource不是空的,它绑定后具有价值到 cbStatus.DataSource = Enum.GetValues(typeof运算(CourseStudentStatus));
The cbStatus.Datasource is not empty and it has value after bound to cbStatus.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
请咨询
推荐答案
以下应该是绑定的最简单方法。
Following should be the simplest way to bind it.
column.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
要获得所选择的价值,你需要将它转换为枚举类型。
To get the selected value you need to cast it to the enum type.
CourseStudentStatus selectedValue = (CourseStudentStatus)column.SelectedValue
Enum.GetValues 的返回enumType值的数组然后可以绑定到任何控制权。
Enum.GetValues returns an array of the enumType values which can then be bound to any control.
我已经在一个独立的测试组合框这个,不是在DataGridView中,情况因人而异。
I've tested this on a standalone combobox, not in a combobox column in DataGridView, YMMV.
这篇关于添加枚举组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!