Lance Ahlberg's WebLog

Reflection on reason

August 2004 - Posts

Binding the GridView control to a complex (deep) business object

MSDN Magazine features a new ASP.NET 2.0 Grid control called GridView.

http://msdn.microsoft.com/msdnmag/issues/04/08/GridView/default.aspx

I have been working with this control in conjunction with an ObjectDataSource in order to display data directly from a domain object.  The GridView in combination with the DataObjectSource allows me to pursue an object driven design in my applications.

I initially setup the GridView in design mode with Bound Fields.  To add the bound fields, I used the field dialog, accessible by clicking on the expand button on the Columns property of the gridView.

This worked fine so long as the domain object that was linked to the ObjectDataSource was “flat”.

So if I had a class...

public OrderItem
{
 private string productName;
 public string ProductName
 {
  get
  {
   return productName;
  }
  
  set
  {
   productName = value;  
  }
 }

 private int orderQuantity;
 public int OrderQuantity;
 {
  get
  {
   return orderQuantity;
  }
  
  set
  {
   orderQuantity = value;
  }
 }

 private decimal productPrice;
 public decimal ProductPrice;
 {
  get
  {
   return productPrice;
  }
  
  set
  {
   productPrice = value;
  }
 }
  
 public OrderItem()
 {
  productName ="";
  orderQuantity = 0;
  productPrice = 0.00M;
 }

}

I can then set the BoundFields DataField property to the OrderItem object properties  ie ProductName, OrderQuantity, or ProductPrice.

But what happens when I have a domain object that is composed of other referenced objects...

public Product
{
 private string name;
 public string Name
 {
  get
  {
   return name;
  }
  
  set
  {
   name = value;  
  }
 }

 private decimal price;
 public decimal Price;
 {
  get
  {
   return price;
  }
  
  set
  {
   price = value;
  }
 }
  
 public Product()
 {
  name ="";
  price = 0.00M;
 }

}

public OrderItem
{
 private Product associatedProduct;
 public Product AssociatedProduct
 {
  get
  {
   return associatedProduct;
  }
  
  set
  {
   associatedProduct= value;  
  }
 }

 private int orderQuantity;
 public int OrderQuantity;
 {
  get
  {
   return orderQuantity;
  }
  
  set
  {
   orderQuantity = value;
  }
 }

 public OrderItem()
 {
  associatedProduct=null;
  orderQuantity = 0;
 }

}

Now when I set the BoundFields DataField property to the Products properties via the OrderItems AssociatedProduct property ie AssociatedProduct.Name or AssociatedProduct.Price the bound field displays a nothing.

In order to get this to work I had to use a TemplateField instead of a BoundField. The field dialog has a nifty link button that can be used to convert the BoundField to a TemplateField. 

All I had to do was create a bound field with a DataField property of AssociatedProduct.Name and then press the “Convert this field into a Template Field“ button and presto the product name was now displaying.

Magic I say..

 

 

More Posts