【问题标题】:Can i use DataGridViewComboBoxColumn to display a list of class objects?我可以使用 DataGridViewComboBoxColumn 来显示类对象列表吗?
【发布时间】:2013-04-29 13:21:29
【问题描述】:

我正在尝试使用类对象列表(ToString 重载)填充DataGridViewComboBoxColumn。这种方法对我来说非常适合常规组合框。但是,一旦我将DataGridViewComboBoxColumn 加载到dataGridView 中,每次我点击远离数据网格时都会引发错误。

这是错误。

The Following Exception Occurred in the DataGridView:
System.ArgumentException: DataGridViewComboBoxCell value is not valid.
To replace this default dialog please handle the DataError event.

这是在错误对话框之前执行的代码:

DataTable dt = new DataTable();

List<mclass> MObjects = new List<mclass>();

DataGridViewComboBoxColumn objcolumn = new DataGridViewComboBoxColumn();

objcolumn.DataSource = MObjects;

objcolumn.ValueType = typeof(mclass);

dataGridView1.DataSource = dt;

dataGridView1.Columns.Add(objcolumn);

现在在错误消息之间,列可以正常工作。我可以完美地从列表中选择对象。如何让这个错误消失并让我的工作组合列安静下来?我错过了什么吗?还是我需要找到一种方法来删除该错误消息?

经过一番研究,我尝试添加这一行:

dt.Columns.Add("OBJList", typeof(mclass));

但是,这会导致相同的例外,更长的时间(我省略了大部分,可根据要求提供):

The following exception occurred in the DataGridView:
System.FormatException: Invalid cast from 'System.String' to 'Namespace.mobject'. --->      
    System.InvalidCastException: Invalid cast from 'System.String' to 'Namespace.mobject'.

【问题讨论】:

  • 可能你的问题是由ComboBoxStyle 是DropDown 引起的,这意味着文本是可编辑的。尝试将样式更改为 DropDownList,这意味着文本不可编辑。
  • 文本当前不可编辑。我相信它是你默认建议的。
  • 好奇者和好奇者。显然,对于任何数据类型,甚至是字符串,这都是 ComboBoxColumn 的常见问题。
  • 我尝试重载datagridview的错误处理,没有结果,代码如下: private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) { anError.Cancel = true;尽管这正确地消除了我心中的错误,但这仍然不起作用。有什么想法吗?

标签: c# .net datagridviewcombobox


【解决方案1】:

我相信你的ValueType 一定是stringtypeof 部分应该是提取值的方法,可能在您的ToString() 中。

【讨论】:

  • 你能详细说明一下吗?我应该在 mclass 类中创建一个返回字符串的方法吗?然后有type=那个方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
相关资源
最近更新 更多