Reputation: 31
I'm trying to fill a DataGridView with values from a DataTable. One of the Columns in the DataGridView should list a ComboBox where the user can select different values from an enum. The initial value should be read from the DataTable
The code:
enum MyEnum {I1 = 1, I2 = 2, I3 = 3}
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("List", typeof(MyEnum));
//fill table
for(int i = 0; i < 10; i++)
{
var row = table.NewRow();
table.Rows.Add(row);
row["ID"] = i;
row["List"] = MyEnum.I2;
}
//build DataGridView and fill it with DataTable
dataGridView1.AutoGenerateColumns = false;
//Column1
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "ID", DataPropertyName = "ID" });
//Column2
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "My Enum Column";
col.DataSource = Enum.GetValues(typeof(MyEnum));
col.ValueType = typeof(MyEnum);
col.DataPropertyName = "List";
dataGridView1.Columns.Add(col);
dataGridView1.DataSource = table;
When executing the code, I get the following error: System.FormatException: Invalid DataGridViewComboBoxCell-Value
The error occurs as soon as I set col.DataPropertyName. So the question is, how do I bind the DataGridViewComboBoxColumn to a DataTable where one Column is filled with values from an enum and through the ComboBox DropDown I can select all values valid for the enum?
thanks for your help
Upvotes: 3
Views: 4392
Reputation: 5266
The solution is to bind the DataGridViewComboBoxColumn.DataSource
to a DataTable
that has two columns, Display
and Value
and set the column's DisplayMember
and ValueMember
properties to the DataTable
column names.
See the accepted answer for: DataGridView linked to DataTable with Combobox column based on enum
Upvotes: 1