![](/img/trans.png)
[英]How to bind a Navigation Property (second level properties) in DataGridView using BindingSource?
[英]How to map properties of inner/nested classes in DataGridView through BindingSource?
我有一個單獨的數據層項目,那里有兩個基本類:
[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]
如何使用BindingSource實現此目的?
我嘗試在DataGridView中使用BindingSource
,但得到的不是5列,而是3(嵌套類被視為一列,應在其中包含內部屬性):
您可以使用要在網格中顯示的所有屬性創建一個新類,然后手動或使用第三方庫(例如AutoMapper)將其與現有類映射。 然后將新類綁定到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;
使用CellFormatting
事件處理程序。 DataGridView.CellFormatting事件
private void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
DataGridViewColumn column = this.dataGridView1.Columns[e.ColumnIndex];
//For getting right column you can compare to the index
//Or as in this example comparing to the names of the predefined columns
if (column.Name.Equals(this.ColumnMapperInfoNumber.Name) == true)
{
MapperInfo temp = e.Value as MapperInfo;
if (temp != null)
e.Value = temp.Number;
}
else if(column.Name.Equals(this.ColumnMapperInfoProp1.Name) == true)
{
MapperInfo temp = e.Value as MapperInfo;
if (temp != null)
e.Value = temp.Prop1;
}
else if(column.Name.Equals(this.ColumnMapperInfoProp2.Name) == true)
{
MapperInfo temp = e.Value as MapperInfo;
if (temp != null)
e.Value = temp.Prop2;
}
}
可以使用的另一種方法是在您的類中重寫.ToString()
方法,
因為DataGridViewTextBoxColumn
將在有界項上執行此方法以獲取顯示的文本(這就是為什么在那里看到類名的原因)。
[Serializable]
public class MapperInfo
{
public string Number { get; set; }
public string Prop1{ get; set; }
public string Prop2 { get; set; }
public override string ToString()
{
return this.Number + ", " + this.Prop1 + ", " + this.Prop2;
}
}
但我擔心這種方法不適合您,因為您希望在不同的列中使用不同的屬性
最終創建了一個用於網格視圖的平面類,並從頭開始使用AutoMapper設置了Mapping:
private void Map(NesInfo ni,out RomInfoView romInfo)
{
Mapper.CreateMap<NesInfo, RomInfoView>()
.ForMember(x => x.MapperNumber, options => options.MapFrom(src => src.MapperInfo.Number))
.ForMember(x => x.Prop1, options => options.MapFrom(src => src.MapperInfo.Prop1))
.ForMember(x => x.Prop2,
options => options.MapFrom(src => src.MapperInfo.Prop2));
romInfo = Mapper.Map<RomInfoView>(ni);
}
如@Vidhyardhi Gorrepati所建議
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.