Last active
December 6, 2017 02:30
-
-
Save LiamKarlMitchell/d0461ea23995a8970fd4bfb51c2efb2a to your computer and use it in GitHub Desktop.
C# Datagrid bind nested properties from data source.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I can't take credit for this but I wanted it as a Gist so I could find it in the future easily if needed. | |
// Found on a blog post by Antonio Bello | |
// http://www.developer-corner.com/blog/2007/07/19/datagridview-how-to-bind-nested-objects/ | |
/// <summary> | |
/// A custom property binder. | |
/// </summary> | |
/// <param name="property"></param> | |
/// <param name="propertyName"></param> | |
/// <returns></returns> | |
public string BindProperty(object property, string propertyName) | |
{ | |
string retValue = ""; | |
if (propertyName.Contains(".")) | |
{ | |
PropertyInfo[] arrayProperties; | |
string leftPropertyName; | |
leftPropertyName = propertyName.Substring(0, propertyName.IndexOf(".")); | |
arrayProperties = property.GetType().GetProperties(); | |
foreach (PropertyInfo propertyInfo in arrayProperties) | |
{ | |
if (propertyInfo.Name == leftPropertyName) | |
{ | |
retValue = BindProperty( | |
propertyInfo.GetValue(property, null), | |
propertyName.Substring(propertyName.IndexOf(".") + 1)); | |
break; | |
} | |
} | |
} | |
else | |
{ | |
Type propertyType; | |
PropertyInfo propertyInfo; | |
propertyType = property.GetType(); | |
propertyInfo = propertyType.GetProperty(propertyName); | |
retValue = propertyInfo.GetValue(property, null).ToString(); | |
} | |
return retValue; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Take your datagrid, add a CellFormatting function. | |
private void dgYourDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) | |
{ | |
if ((dgYourDataGrid.Rows[e.RowIndex].DataBoundItem != null) && | |
(dgYourDataGrid.Columns[e.ColumnIndex].DataPropertyName.Contains("."))) | |
{ | |
e.Value = Misc.BindProperty( | |
dgYourDataGrid.Rows[e.RowIndex].DataBoundItem, | |
dgYourDataGrid.Columns[e.ColumnIndex].DataPropertyName | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment