在创建一个DataGridView下拉从枚举列表选项创建一个、选项、列表、DataGridView

2023-09-02 01:50:15 作者:流氓痞性

我现在有一个类,我试图创建一个简单的图形用户界面来创建这个类的一个集合。大多数此类的属性是字符串。不过,我希望用户能够设置的属性之一是一个枚举。因此,我想在用户界面,有一个DropDownList此枚举,从输入值无效限制用户。目前,我正在对象初步名单,将它们添加到DataTable和我的DataGridView的数据源设置为表。工作得很好,甚至创造了一个布尔属性的复选框列。但是,我不知道如何使列枚举成一个DropDownList。我使用C#和.NET 2.0。

I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.

另外,我已经试过分配的DataGridView的数据源到我的对象的列表中,但是当我这样做,它不会帮助枚举,我无法在DataGridView中创建新行,但我我绝对不会绑定到使用数据表作为我的数据源,它只是选择我有半的工作。

Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.

推荐答案

我不知道这是否将与一个DataGridView列,但它与组合框:

I do not know if that would work with a DataGridView column but it works with ComboBoxes:

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

MyEnum value = (MyEnum)comboBox1.SelectedValue;

更新:它与DataGridView列太,只记得要设置的值类型

UPDATE: It works with DataGridView columns too, just remember to set the value type.

DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "My Enum Column";
col.DataSource = Enum.GetValues(typeof(MyEnum));
col.ValueType = typeof(MyEnum);
dataGridView1.Columns.Add(col);