我正在尝试创建一个绑定到 DataTable 的 DataGridView,其中一列是 ComboBox。代码运行,但在绑定后(不是在绑定数据时)出现以下错误:System.ArgumentException:DataGridViewComboBoxCell 值无效。
在 DataGridView 中,其中一列是 DataGridViewComboBoxColumn,它使用枚举(名为 StructureType)作为其源:
// ColumnStructure
//
this.ColumnStructure.ValueType = typeof(structureType);
this.ColumnStructure.DataSource = Enum.GetValues(typeof(structureType));
this.ColumnStructure.HeaderText = "Structure";
this.ColumnStructure.Name = "ColumnStructure";
this.ColumnStructure.DataPropertyName = "Structure";
//
当我在不使用 DataTable 的情况下填充 DataGridView 时,它工作得很好:
structureType? structure = GetStructure(part);
dgvObjectTypes.Rows.Add(name, type, structure, count);
现在我想使用 DataTable 代替,但无法让它工作。数据表创建如下:
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Type", typeof(string));
table.Columns.Add("Structure", typeof(DataGridViewComboBoxCell));
table.Columns.Add("Count", typeof(int));
其他列工作得很好,但我无法让“结构”列工作。这是我尝试创建组合框的方法:
var cb = new DataGridViewComboBoxCell();
cb.ValueType = typeof(structureType);
cb.DataSource = Enum.GetValues(typeof(structureType));
cb.Value = (structureType)structure;
之后,我只需为表创建行并将表设置为 DataGridView 的数据源:
table.Rows.Add(name, type, cb, count);
dgv.DataSource = table;
我读过很多文章,其中指出在组合框中使用枚举会导致问题(例如:DataGridView 通过基于枚举的 Combobox 列链接到 DataTable),但这里的情况似乎并非如此。我什至尝试使用显式类型化的字符串数组,但仍然遇到相同的错误。我认为我对 DataGridViewComboBoxCell 做错了什么。
可能是什么问题呢?