假设有一个类
class Person { private string id; private string name; private Address homeAddr; public string ID { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public Address HomeAddr { get { return homeAddr; } set { homeAddr = value; } } } class Address { private string cityname; private string postcode; public string CityName { get { return cityname; } set { cityname = value; } } public string PostCode { get { return postcode; } set { postcode = value; } } }
将类绑定到Datagridview
List<Person> lst = new List<Person>(); for (int i = 0; i < 10000; ++i) { lst.Add(new Person() { ID = "1", Name = "name", HomeAddr = new Address() { CityName = “CityName”, PostCode = “PostCode ”} }); } dataGridView1.DataSource = lst;
其实值已经有了,只是Datagridview不显示。可以通过DataPropertyName指定子属性名字,在CellFormatting事件中通过反射获取。
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if ((dataGridView1.Rows[e.RowIndex].DataBoundItem != null) && (dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Contains("."))) { string[] names = dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Split(‘.‘); object obj = dataGridView1.Rows[e.RowIndex].DataBoundItem; for (int i = 0; i < names.Count(); ++i) { try { var result = obj.GetType().GetProperty(names[i]).GetValue(obj, null); obj = result; e.Value = result.ToString(); } catch (Exception) { return; throw; } } } }
结果发现Datagridview列多了
可以指定dataGridView1的AutoGenerateColumns属性为false,让datagridview不自动生成列。(要在绑定前指定)
- 如果字属性只有一个属性要显示,可以直接override字属性的ToString方法。
- msdn上有人用特性实现,不过我试了下貌似不行。http://blogs.msdn.com/b/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a-second-level-property-of-a-data-source.aspx