public void BindControlToObject(Control control, object bindObject) {
foreach(System.Reflection.PropertyInfo property in bindObject.GetType().GetProperties()) {
HtmlInputControl foundControl = control.FindControl(property.Name) as HtmlInputControl;
if(foundControl != null) {
property.SetValue(bindObject, foundControl.Value, null);
}
}
}
public void BindObjectToControl(Control control, object bindObject) {
foreach(System.Reflection.PropertyInfo property in bindObject.GetType().GetProperties()) {
Control foundControl = control.FindControl(property.Name);
if(foundControl != null) {
if(foundControl is Label) {
((Label)foundControl).Text = property.GetValue(bindObject, null).ToString();
}
}
}
}
This will handle the mapping between form fields and our business layer classes. Now, we can use these two helper methods to handle the mapping between business layer classes and DataRows:
public void BindObjectToDataRow(object bindObject, DataRow dataRow) {
foreach(System.Reflection.PropertyInfo property in bindObject.GetType().GetProperties()) {
if(dataRow.Table.Columns.Contains(property.Name)) {
dataRow[property.Name] = property.GetValue(bindObject, null);
}
}
}
public void BindDataRowToObject(object bindObject, DataRow dataRow) {
foreach(System.Reflection.PropertyInfo property in bindObject.GetType().GetProperties()) {
if(dataRow.Table.Columns.Contains(property.Name)) {
property.SetValue(bindObject, dataRow[property.Name], null);
}
}
}
I don't think it would require much imagination to come up with something that would handle the mapping between business layer classes and stored procedure parameters. Any ideas?
I'm sure there are performance issues for using reflection in this way, but when you think about how emporing these techniques can be for you as a developer, these issues seem a lot less important. They can allow you to focus on the true engineering challenges of web application building, rather than spending hours creating endless mappings between tiers.