How to show Enum type members in a DataGridViewComboBox?
Adding to the answer Bradly Smith provided: One can get all Enum values (instead of naming each individually) easily using this code:
ReadDataGridViewComboBoxColumn.DataSource =
new List<ReadAccess>((ReadAccess[]) Enum.GetValues(typeof(ReadAccess)))
.Select(value => new { Display=value.ToString(), Value=(int)value })
.ToList();
This is a problem i've come across many times. The DataGridViewComboBoxColumn
doesn't know how to reconcile the difference between the enum's string representation and its integral value. Even though you set ValueType
to the type of the enum, the DataGridView
will try to set the cell's value to the underlying int
value - this is why a FormatException
will be raised during databinding.
The only way i've found to overcome this problem (short of subclassing the cell type) is to bind the DataGridViewComboBoxColumn
to a data source which separates the string values from the integer values. You can use an anonymous type for this purpose:
ReadDataGridViewComboBoxColumn.ValueType = typeof(ReadAccess);
ReadDataGridViewComboBoxColumn.ValueMember = "Value";
ReadDataGridViewComboBoxColumn.DisplayMember = "Display";
ReadDataGridViewComboBoxColumn.DataSource = new ReadAccess[]
{ ReadAccess.None, ReadAccess.Allowed }
.Select(value => new { Display=value.ToString(), Value=(int)value })
.ToList();
This way, the DataGridView
knows how to relate the cell value with its formatted value.