Table of Contents

When we consume business objects in UI, the logic can become pretty complex for activities like setting the business object value, getting the object value and setting the user interface from the object value. We can minimize the complexity of UI interaction with the business object using mediator pattern.

I have been writing and recording a lot of architecture related videos on design patterns, UML, FPA estimation, C# projects, etc. You can watch my videos here.

The answer to this is if we can make a mediator who takes care of which UI objects map which object property that will solve our problem. So what we need to do is implement a simple UI object connector which takes the values from UI and sets to the object. This can be easily implemented by using mediator pattern. In case you are not aware of it, you watch this video to understand the concept.

For the mediator class, we will have two array lists - one which will have the text box and the other will have the property. Every item of the array, i.e. Text box will have a corresponding item of property where the value will be set:

To set the values from the object to the UI, we will use reflection. So get the text box and the corresponding property and set the same using reflection:

publicvoid setValuesToObject(clsSampleClass objSample)
{
// get the object type
Type objType = objSample.GetType();
// browse through all the UI objects and set the object// from the UI to the corresponding propertyfor(int i=0;i<objtextboxes.Count;i++)
{
// get the UI object
PropertyInfo objProperty = objType.GetProperty(objPropertyInfo[i].ToString());
// set the object property from the UI object
objProperty.SetValue(objSample,((TextBox)objtextboxes[i]).Text,null);
}
}

Comments and Discussions

Good article ... but its not bad ... you see this is a good idea to shorten code ... but we are talking about really simple scenarios ... not the complex ones or even not the everyday cases we meet ...

I think we should take this in consideration ... no doubt ... but it needs to be more generalized to involve the more complex scenarios we might face (we will face for sure )

Sincerely Samer Abu Rabie

Note: Please remember to rate this post to help others whom reading it.

Yeah. There must be so many other solutions to this out there. I think every single programmer that has ever created a form for capturing data into an object has done this kind of thing.

Your solution is quite elegant for simple cases. I like it.
The one challenge that would need to be addressed though is handling the different control and data types, but I do understand that this is a demonstration of the Mediator patter, not a cure for the world's problems
It's nice to see someone else thinking in design patterns.