从 DataGridView 中的枚举创建下拉列表选项 [英] Create drop down list options from enum in a DataGridView

查看:29
本文介绍了从 DataGridView 中的枚举创建下拉列表选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个类,我正在尝试创建一个简单的 GUI 来创建此类的集合.这个类的大部分属性都是字符串.但是,我希望用户能够设置的属性之一是枚举.因此,我希望用户界面具有此枚举的下拉列表,以限制用户输入无效值.目前,我正在获取对象的初始列表,将它们添加到 DataTable 并将我的 DataGridView 的 DataSource 设置到表中.效果很好,甚至为一个布尔属性创建了一个复选框列.但是,我不知道如何将枚举的列变成下拉列表.我使用的是 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 的 DataSource 分配给我的对象列表,但是当我这样做时,它对枚举没有帮助,而且我无法在 DataGridView 中创建新行,但是我我绝对不会使用 DataTable 作为我的数据源,这只是我半工作的选项.

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 列,但适用于 ComboBox:

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);

这篇关于从 DataGridView 中的枚举创建下拉列表选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆