Reputation: 2620
I couldn't find a question on SO that exactly matched my problem.
Similar to this question and this question, I'm setting the DataSource
on a DataGridViewComboBoxColumn
to a list of things. In my case the things are simple types like doubles and ints, so the answers talking about ValueMembers and DisplayMembers don't do me a lot of good. When the user selects a value I get the dreaded "DataGridViewComboBoxCell value is not valid" error.
I could swallow the error with an empty dataGridView_DataError handler, but that is obviously a bad way to go.
Upvotes: 7
Views: 22843
Reputation: 436
I struggled with the same type of issue and figured I would answer what I did to correct this issue.
List<int> myList = new List<int>();
//Populate list with data
DataGridViewComboBoxColumn c1 = new DataGridViewComboBoxColumn();
c1.ValueType = typeof(int);
c1.DataSource = myList;
dataGridView.Columns.Add(c1);
I hope I can help someone who still has this issue.
Upvotes: 0
Reputation: 1065
The problem for me was that the value my datasource was returning was not available in the combobox.... my combo had value 1, 2 and 3... but datasource wanted 4.
Upvotes: 0
Reputation: 1
This is finicky about sub-types. I still got the error when the ValueType was Int, but the DataSource contained a SQLServer SMALLINT (which a Visual Studio 2010 Quick-Watch on the DataSource said was an Int32 !). Changing the DB column from SMALLINT -> INT fixed it for me.
Upvotes: 0
Reputation: 2620
I found the answer here. It's also mentioned in this answer to the second link in my question. When setting the DataSource
to a list of anything that's not a string, set the ValueType
of the column to typeof(<your data type>)
IList<double> kvChoices;
// Populate kvChoices...
DataGridViewComboBoxColumn kvCol =
dataGridView1.Columns[0] as DataGridViewComboBoxColumn;
kvCol.DataSource = kvChoices;
kvCol.ValueType = typeof(double);
Upvotes: 21