Thursday, April 05, 2007

Binding ASP .NET 2.0 GridView to a complex object using ObjectDataSource

The ObjectDataSource provided with ASP .NET 2.0 allows a GridView component to be bound a list of user defined objects. The columns in the gridview could be defined as "BoundFields", binding the column to a particular property of the user defined object.

However, this works fine, as long as the object is flat. In the current project that I am working on, we had a class structure as given below:

class ShoppingCartItem
{
int requestedQuantity;
ProductInfo product;
}

class ProductInfo
{
string productName;
string brandName;
}

We wanted to show the Product Name, Brand Name and Requested Quantity of each product in the Shopping Cart of the user in a tabular format using the GridView control. We were using the ObjectDataSource and binding the GridView with a list of ShoppingCartItem instances. Now, the problem was that the product name and brand name were not directly accessible from the ShoppingCartItem class. Instead they were properties inside the ProductInfo class, that was a part of the ShoppingCartItem class.

Solutions:

1. This particular problem could have been solved by using the TemplateField and the DataBinder.eval approach, but that meant changing a lot of things in the page.

2. Instead, a clean, quick and yet a very simple solution to this problem was to add wrapper methods inside the ShoppingCartItem class to get the product name and the brand name from the ProductInfo class. We could easily bind the column of the GridView to these wrapper methods inside the ShoppingCartItem class.

4 comments:

Siddhesh said...

Good to see .NET articles from you :) I hope the transformation is complete!

James Yoo said...

This will not work for 2-way binding, only for display purposes. Any help for 2-way binding, so one can do updates?

Arati Rahalkar said...

James - I am afraid with the ObjectDataSource approach, you pretty much have to handle the updates / deletes etc. yourself.

It isn't like the regular SqlDataSource that can store the list of updates / changes for you and do the updates for you automatically.

With ObjectDataSource, you are most of the times using the Connected architecture to read the data from the database and then populate the objects, unlike the Disconnected architecture used with a SqlDataSource typically..

Armando MorĂ¡n said...

This worked fine for me, cool post...