今天我们来讨论下一个实体中某个属性又是实体的类型的集合绑定到DataGridView上的问题。
我们可以看到Result中有一个属性Student的类型是另外一个实体类Student。
01.如果能保证在实体Result中的Student属性到时候在界面上行只显示Student中的一个属性,例如StudentName,那么我们重写Student的ToString()方法来达到目的。
02.这时候只需要设置DataPropertyName的值为Student,即可,因为设置了Student后,会自动调用它的ToString()方法将StudentName返回。
方案二:在DataGridView控件中,通过在CellFormatting事件中通过反射获取。
02.这时候要给DataPropertyName属性赋值为Student.StudentName
解析:这种方式可以处理Student中多列出现在DataGridView中的情况,是比较好的解决方案。而且这样解决方案可以处理Result中引入多个外部实体的属性的情况。
方案三:同方案二一样:msdn提供的一种方式,但是会报错,暂时收录:
The following is the code for class Person and Address.
List<Person> persons = new List<Person>();
// add some Person objects to the collection
dataGridView1.DataSource = persons;
dataGridView1.Columns[0].DataPropertyName = "ID";
dataGridView1.Columns[1].DataPropertyName = "Name";
dataGridView1.Columns[2].DataPropertyName = "HomeAddr";
The following is the code of a custom class that derives from PropertyDescriptor.
The following is the code of a derived CustomTypeDescriptor class.
The following is the code of the custom TypeDescriptorProvider.
At the end, we adorn TypeDescriptionProviderAttribute to the class Person.
[TypeDescriptionProvider(typeof(MyTypeDescriptionProvider))]
dataGridView1.Columns[2].DataPropertyName = "HomeAddr_CityName";
dataGridView1.Columns[3].DataPropertyName = "HomeAddr_PostCode";
联系客服