C# 错误:“DataGridViewComboBoxCell 值无效。” DataSource 是基本类型的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13461885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:40:04  来源:igfitidea点击:

Error: "DataGridViewComboBoxCell value is not valid." DataSource is list of basic type

c#datagridview

提问by Chuck Wilbur

I couldn't find a question on SO that exactlymatched my problem.

我在 SO 上找不到与我的问题完全匹配的问题。

Similar to this questionand this question, I'm setting the DataSourceon a DataGridViewComboBoxColumnto 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.

this questionthis question类似,我将DataSourcea设置DataGridViewComboBoxColumn为一个列表。在我的情况下,事情是简单的类型,比如双精度和整数,所以关于 ValueMembers 和 DisplayMembers 的答案对我没有多大好处。当用户选择一个值时,我会收到可怕的“DataGridViewComboBoxCell 值无效”错误。

I could swallow the error with an empty dataGridView_DataError handler, but that is obviously a bad way to go.

我可以用一个空的 dataGridView_DataError 处理程序吞下错误,但这显然是一个糟糕的方法。

采纳答案by Chuck Wilbur

I found the answer here. It's also mentioned in this answerto the second link in my question. When setting the DataSourceto a list of anything that's not a string, set the ValueTypeof the column to typeof(<your data type>)

我在这里找到了答案。在我的问题中第二个链接的答案中也提到了这一点。将 设置DataSource为非字符串的任何列表时ValueType,将列设置为typeof(<your data type>)

        IList<double> kvChoices;
        // Populate kvChoices...
        DataGridViewComboBoxColumn kvCol =
            dataGridView1.Columns[0] as DataGridViewComboBoxColumn;
        kvCol.DataSource = kvChoices;
        kvCol.ValueType = typeof(double);

回答by Craig

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 wasan Int32 !). Changing the DB column from SMALLINT -> INT fixed it for me.

这对子类型很挑剔。当 ValueType 为 Int 时,我仍然遇到错误,但 DataSource 包含 SQLServer SMALLINT(DataSource 上的 Visual Studio 2010 Quick-Watch 说它Int32 !)。将 DB 列从 SMALLINT -> INT 更改为我修复了它。

回答by SerenityNow

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.

我的问题是我的数据源返回的值在组合框中不可用....我的组合具有值 1、2 和 3...但数据源想要 4。