C # WinForm DataGridView enable DataPropertyName to support complex attributes,
First, add BindingSource to the Grid. The type is bindingform2. Alternatively, set the DataSource of the Grid to IEnumerable <bindingform2>.
The BindingForForm2 type is as follows.
public class BindingForForm2 { public int Age { get; set; } public string Name { get; set; } public int Height { get; set; } public int Weight { get; set; } public ClassTest ClassTest { get; set; } } public class ClassTest { public string S1 { get; set; } public string S2 { get; set; } }View Code
We want to directly display the S1 and S2 attributes of the ClassTest attribute in bindingform2 on the Grid. For example, set DataPropertyName. Set the use of vertex directly.
Register the CellFormatting event of the DataGridView as follows. The Code roughly means that the Object in the selected row is obtained first (bindingform2 here), then the DataPropertyName setting is obtained, and the expected value is read through reflection.
1 private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 2 { 3 if (e.Value != null) return; 4 try 5 { 6 var dgv = (DataGridView)sender; 7 object obj = null; 8 var source = dgv.DataSource as BindingSource; 9 if (source != null)10 {11 obj = ((IEnumerable<object>)source.DataSource).ElementAt(e.RowIndex);12 }13 else if (dgv.DataSource is IEnumerable<object>)14 {15 obj = ((IEnumerable<object>)dgv.DataSource).ElementAt(e.RowIndex);16 }17 var col = dgv.Columns[e.ColumnIndex];18 var props = col.DataPropertyName.Split('.');19 foreach (var prop in props)20 {21 if (obj == null) return;22 var p = obj.GetType().GetProperty(prop);23 if (p == null) return;24 obj = p.GetValue(obj, null);25 }26 e.Value = obj;27 }28 catch29 {30 //ignore31 }32 }
Effect:
BindingSource fill data
bindingForForm2BindingSource.DataSource = new List<BindingForForm2> { new BindingForForm2 {Age = 10, Height = 120, Name = "xxx", ClassTest = new ClassTest {S1 = "sdjfkljlk"}}, new BindingForForm2 {Age = 12, Height = 120, Name = "asd", ClassTest = new ClassTest {S2 = "ccccccc"}}, new BindingForForm2 {Age = 14, Height = 120, Name = "asdd"} };View Code
GridView display
Indicate the source for reprinting. Http://www.cnblogs.com/JmlSaul/p/7726233.html