如何将 DataGridViewComboBoxColumn 绑定到对象? [英] How to bound a DataGridViewComboBoxColumn to a object?
问题描述
我正在尝试将 DataGridViewComboBoxColumn
绑定到 Foo 的实例,但是当我在网格上设置一个值时,我收到一个 ArgumentException
告诉我我不能从字符串转换为 Foo.
I'm trying to bound a DataGridViewComboBoxColumn
to an instance of Foo, but when i set a value on the grid i got a ArgumentException
telling me that i can not convert from String to Foo.
var data = (from item in someTable
select new { Foo = item.foo, Bar = item.Bar }).ToList();
grid.DataSource = data;
column.DataPropertyName = "Foo";
column.DataSource = (from foo in Foo select foo).ToList (); //foo is an instance of Foo
column.DisplayMember = "SomeNameField"; //Foo.SomeNameField contains a description of the instance
我错过了什么吗?是否可以将数据绑定到复杂对象?
Am i missing something? is it possible to databind to a complex object?
更新:
我实现了一个 TypeConverter 并覆盖了 CanConvertFrom、CanConvertTo、ConvertTo、ConvertFrom.现在我得到了
I implemented a TypeConverter and overrided CanConvertFrom, CanConvertTo, ConvertTo, ConvertFrom. Now i'm getting
FormatException: DataGridViewComboBoxCell 值无效
FormatException: The DataGridViewComboBoxCell value is not valid
有什么想法吗?
推荐答案
您遗漏了一个可能的部分.
You are missing a possible piece.
column.DataPropertyName = "Foo";
column.DisplayMember = "SomeNameField";
column.ValueMember = "Bar"; // must do this, empty string causes it to be
// of type string, basically the display value
// probably a bug in .NET
column.DataSource = from foo in Foo select foo;
grid.DataSource = data;
更新:
实际上,在再次阅读您的问题后,我认为您正面临着该错误.不幸的是,如果不使用自定义 TypeDescriptor/TypeConverter/BindingSource,则无法使其返回绑定对象.
Actually, after reading your question again, I think you are facing that noted bug. There is unfortunately no way to make it return the bound object without using a custom TypeDescriptor/TypeConverter/BindingSource.
绑定到复杂对象的答案.默认没有.我为我当前的项目写了一篇很好的文章.这涉及制作一个返回所有嵌套属性的自定义 TypeDescriptor/TypeConverter/BindingSource.另一个错误",您不能使用."对于成员分隔符,我不得不求助于:".
Answer for binding to a complex object. No by default. I wrote quite a nice one for my current project. This involves making a custom TypeDescriptor/TypeConverter/BindingSource that returns all the nested properties. Another 'bug', you cant use '.' for a member separator, I had to resort to ':' instead.
这篇关于如何将 DataGridViewComboBoxColumn 绑定到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!