Monday, November 5, 2007

Binding a complex object to DetailsView

One of the common requirements while building an application is to bind to your domain objects. .Net has some excellent features for doing this.

Recently I was experimenting with Details view and binding it to a domain specific object. The default binding works fine if the object properties are of simple type.

What if the Object has a property that itself is an object. Assume that we have a user object which represents a user in the application [like a customer]. The user will have a name, age. So far it’s good. The default binding will bind to the objects simple properties.

But Customers will have addresses. For dealing with this usually we create an address object and expose it as a property of the User object. Now if you bind the user object to the DetailsView the default data binding skips the address property.

Ok, how to get your customers address displayed in the details view. There are a couple of was to do it.

If you are just concerned about displaying data, then the short and easy way is to override the ToString() method of the inner objects. For example if you override the ToString() method of the Address object so that it returns a string which contains all the address information, then the default binding will display the address! If you follow this path and if you are not careful your object might end up knowing all the display details.

Another way is to use and template fields in combination. But this is one way binding. We have to write up code that hooks up to proper events for editing and inserting. We can not use the Bind method for two way binding. It raises an error saying that the syntax for the binding expression is not correct.

One another approach is to create custom DataControlField object which can handle the inner object of type Address. Dino Esposito has a very good article on this @ http://msdn.microsoft.com/msdnmag/issues/06/01/CuttingEdge/. You can follow this approach if we need more specialized presentation.

Saravanan Kanagaraj