如何通过BindingSource映射DataGridView内/嵌套类的属性? [英] How to map properties of inner/nested classes in DataGridView through BindingSource?
问题描述
我有一个单独的数据层项目,有两个基本类:
I have a separate project for Data layer and there are two basic classes there:
[Serializable]
public class NesInfo
{
public string FileName { get; private set; }
public string Directory { get; private set; }
public MapperInfo MapperInfo { get; set; }
}
和
[Serializable]
public class MapperInfo
{
public string Number { get; set; }
public string Prop1{ get; set; }
public string Prop2 { get; set; }
}
现在我要我的DataGridView显示这样的列:
[FileName] [Directory] [Number] [Prop1] [Prop2]
Now I want my DataGridView to Display columns like this:
[FileName][Directory][Number][Prop1][Prop2]
这使用BindingSource?
How I can achieve this using BindingSource?
我试过在我的DataGridView中使用我的 BindingSource
,而不是5列获取3(嵌套类被视为一列,内部属性应该在那里):
I've tried using my BindingSource
in my DataGridView, but instead of 5 columns, I get 3 (the nested class is treated like one column, where the inner properties should be there instead):
当尝试添加列时,我无法选择MapperInfo类的内部属性:
And I cannot select the inner properties of MapperInfo class when trying to add columns:
推荐答案
您可以创建一个包含所有属性的新类您希望在网格中显示,并将其与您现有的类别手动或使用第三方库(例如, AutoMapper)。然后将新类绑定到网格。
You can create a new class with all the properties that you want to be display in the grid and map it with your existing class either manually or using third-party libraries (ex. AutoMapper). Then bind the new class to Grid.
public class MyGridClass
{
public string FileName { get; set; }
public string Directory { get; set; }
public string Number { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
NesInfo ni = ...
MyGridClass gc = new MyGridClass ( );
gc.FileName = ni.FileName;
gc.Directory = ni.Directory;
gc.Number = ni.MapperInfo.Number;
gc.Prop1 = ni.MapperInfo.Prop1;
gc.Prop2 = ni.MapperInfo.Prop2;
这篇关于如何通过BindingSource映射DataGridView内/嵌套类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!