Thursday, April 12, 2012

Asp.NET data binding: Object does not match target type.

Every day is a new adventure .. Today I face this "funny" behaviour of the ASP.NET "data binding".

I'm working on ASP.NET webform application, and a piece of this application must automatically generate some documents, nearly all PDF.
The documents are all heterogeneous, and in an object oriented way, I decided to implement a interface on each class able to generate a document.

The interface IDocumentoSemplice is pretty trivial and have only few properties.



What I like to do, is gather all possible documents for a user, and show them in a GridView.
The documents are loaded in a service class and then bounded to the GridView for the "DataBind".
The columns in the page are nearly all BoundField.

   <asp:boundfield datafield="DataCompilazione" dataformatstring="{0:d}"  
                   headertext="Data Compilazione">
   </asp:boundfield>

All seems to be great, but when I start the page, this exception pop up: "Object does not match target type."

I check and recheck the code, but cannot find anything wrong.
Finally I googled a bit for this problem, and what I found is pretty funny: the "DataBind" (at least the GridView one) need all the data-bounded objects are to be of the same type.

The solution was pretty simple: convert all the bounded field in template one:

   <asp:TemplateField>
      <ItemTemplate>
         <%# Server.HtmlEncode(((IDocumentoSemplice)Container.DataItem)
                               .DataCompilazione.ToShortDateString())%>
      </ItemTemplate>
   </asp:TemplateField>



The problem seem to be caused by some internal classes used for the reflection, needed to get the properties value at runtime.


Happy "DataBind" ...

2 comments: