问题
I have a DataGridView in my .NET 4.5 WinForms app with two columns. One column is a regular textbox column and the other column is a DataGridViewComboBoxColumn
that is a dropdown. I am trying to bind the columns to a BindingList
of my Filter
object and I would like everything inside of the enum FilterType
to show up in the dropdown. Here's the code for my object and enum:
public class Filter
{
public string keyword { get; set; }
public FilterType type { get; set; }
}
public enum FilterType : int //the strings should appear in the dropdown
{
SESSION = 1,
ORDER = 2,
SHIPMENT = 3
}
I have manually created the columns in the VS 2012 designer where I changed the ColumnType
, HeaderText
, and DataPropertyName
to keyword
and type
.
Using an answer I found here I have added these two lines of code to my form loading event:
colFilterType.DataSource = Enum.GetValues(typeof(FilterType));
colFilterType.ValueType = typeof(FilterType);
When I run the code I initially see a blank row. Whenever I click on the row, irregardless of which column is clicked, I get a pop-up error.
System.ArgumentException: DataGridViewComboBoxCell value is not valid. ... please handle the DataError event.
I can ignore it and type whatever text I want into the Keyword
column, and the dropdown is magically filled in with the first value of the enum. However, if I even mouse-over the dropdown the error pops up again (please see the screenshot). I am not sure what causes the error and don't know where to set a breakpoint. I also do not know if I'm creating the problem by making parts of the DataGridView in the designer and modifying those in code. The designer does not let me set the DataSource
the way I did in the code. It also contains a field ValueMember
that I haven't seen used in code.

Although not ideal, I wouldn't mind catching the error and doing nothing with it since the dropdown seems to populate itself (and assuming all the data stays intact).
回答1:
Your code works fine when adding the column at runtime. Sample code:
DataGridViewComboBoxColumn colFilterType = new DataGridViewComboBoxColumn();
colFilterType.HeaderText = "Name you want";
colFilterType.DataSource = Enum.GetValues(typeof(FilterType));
colFilterType.ValueType = typeof(FilterType);
dataGridView1.Columns.Add(colFilterType);
Errors like the one you report are usually provoked while changing the type of a cell/column at runtime, because of the big number of events which are triggered every time a DataGridView
is affected in any way: some of them expect the old type and find elements with the new one (e.g., expecting an int
and finding a string
).
来源:https://stackoverflow.com/questions/20359317/datagridview-default-error-on-combobox-column