First, add the BindingSource to the grid, and the type is BINDINGFORFORM2. or set the DataSource of the grid to ienumerable<bindingforform2>.
The BINDINGFORFORM2 types are as follows.
Public classBindingForForm2 { Public intAge {Get;Set; } Public stringName {Get;Set; } Public intHeight {Get;Set; } Public intWeight {Get;Set; } PublicClasstest Classtest {Get;Set; } } Public classClasstest { Public stringS1 {Get;Set; } Public stringS2 {Get;Set; } }
View Code
We want to display the S1 and S2 properties of the Classtest property in BindingForForm2 directly on the grid. Can be set as DataPropertyName. Set the way you use attribute points directly.
You can then register the DataGridView cellformatting event as follows. The code basically means to take the object of the currently selected line (BindingForForm2 here), then take the DataPropertyName setting, and then loop through the reflection to read the desired value.
1 Private voidDatagridview1_cellformatting (Objectsender, Datagridviewcellformattingeventargs e)2 {3 if(E.value! =NULL)return;4 Try5 {6 varDGV =(DataGridView) sender;7 Objectobj =NULL;8 varSource = DGV. DataSource asBindingSource;9 if(Source! =NULL)Ten { Oneobj = ((ienumerable<Object>) source. DataSource). ElementAt (e.rowindex); A } - Else if(DGV. DataSource isienumerable<Object>) - { theobj = ((ienumerable<Object>) DGV. DataSource). ElementAt (e.rowindex); - } - varCol =DGV. Columns[e.columnindex]; - varprops = Col. Datapropertyname.split ('.'); + foreach(varPropinchprops) - { + if(obj = =NULL)return; A varp =obj. GetType (). GetProperty (prop); at if(p = =NULL)return; -obj = P.getvalue (obj,NULL); - } -E.value =obj; - } - Catch in { - //Ignore to } +}
Effect:
BindingSource Populating data
Bindingforform2bindingsource.datasource =NewList<bindingforform2> { NewBindingForForm2 {age =Ten, Height = -, Name ="XXX", classtest =Newclasstest {S1 ="Sdjfkljlk"}}, NewBindingForForm2 {age = A, Height = -, Name ="ASD", classtest =Newclasstest {S2 ="CCCCCCC"}}, NewBindingForForm2 {age = -, Height = -, Name ="ASDD"} };
View Code
GridView Display
Reprint please indicate the source. Http://www.cnblogs.com/JmlSaul/p/7726233.html
C # WinForm DataGridView let DataPropertyName support complex properties