寻找解决DataGridView控件无法绑定到分层(OO)数据的方法 [英] Looking for work-around for inability of DataGridView control to bind to hierarchical (OO) data
问题描述
看来,DataGridView控件只能绑定到平面的数据源(所有属性都是主要类型)。我的数据是分层的。例如:
It would seem that the DataGridView control can only bind to data sources that are flat (all the Properties are primative types). My data is hierarchal. For example:
interface INestedObj
{
string Prop3 { get; }
}
interface IParentObj
{
public string Prop1 { get; }
public string Prop2 { get; }
public INestedObj NestedObj { get; }
}
给定这个,如何绑定一个实现IParentObj的对象?最终你必须做这样的事情:
Given this, how does one bind to an object implementing IParentObj? Eventually you are faced with having to do something like this:
grid.Columns["prop1Col"].DataPropertyName = "Prop1";
grid.Columns["prop2Col"].DataPropertyName = "Prop2";
grid.Columns["prop3Col"].DataPropertyName = "How to display Prop3?";
grid.Columns["prop3Col"].DataPropertyName = "NestedObj.Prop3"; // does not work
我正在寻找建议和/或解决方法。
I am looking for advice and/or work-arounds.
TIA
推荐答案
这是一个简单的解决方案,一个很长的一天。
Here is a simple solution that came to me at the end of a long day.
我使用Linq查询和投影来创建一个匿名类型,在DataGridView中显示正确的信息。
I used a Linq query and projection to create an anonymous type that displays the proper information in the DataGridView.
var query = from pt in parentObjCollection
select new {Prop1=pt.Prop1, Prop2=pt.Prop2, NestedObj.Prop3=pt.NestedObj.Prop3};
我必须提供适当的值(NestedObj.Prop3)到DataPropertyName属性来获取值在网格中显示。
I had to supply the proper value (NestedObj.Prop3) to the DataPropertyName property to get the value to display in the grid.
当我有更多的时间要尝试和实施Bradley的解决方案。
When I have more time I am going to try and implement Bradley's solution.
这篇关于寻找解决DataGridView控件无法绑定到分层(OO)数据的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!