Wednesday, January 21, 2009

Asp.net DataObjectSource + Gridview difficulty

Here are some annoyances I encountered recently while trying to get some basic data binding to work in ASP.NET:

I was using an ObjectDataSource to access objects through our data access layer, and then displaying the data in a Gridview. After some tweaking, I got it to display all right, but when I clicked "Edit" and then "Update" I ran into all kinds of issues. First it wouldn't link up right to my data access layer, because it was looking for a method that included the Name and Description fields. After some digging around, I found out that the "Default" method it looks for is one with only an object (in this case of a type called TrackedEntity) as a parameter. But because the data access layer's default add/update/delete methods also include a boolean parameter to tell it whether or not to Save the updated changes (though I have a hard time imagining why you wouldn't want it to, if you're calling the Update method), ASP.NET got kicked out of this default object-oriented mode, and started looking instead for a method that took all the parameters it knew about, plus the ones that I specified. Fix: create an update method that only takes a TrackedEntity, and point the ObjectDataSource to that method.

After this, however, it still couldn't update correctly because the TrackedEntity object it was updating was only getting instantiated with its Name and Description (and not its ID). So when the data access layer tried loading up the object to update, it couldn't find an object with an ID of zero, so it died.

As a work-around, I found that simply including the ID column in the GridView would do the trick, but that's a hack, at best. After much searching, I found out that GridViews have a DataKeyNames property, in which you can include a comma-separated list of fields that shouldn't be shown in a column, but which need to be persisted so that the object being saved gets instantiated with all its previous values.

Finally, if I left any of the fields blank, it would complain that the values could not be null.  By default, Gridviews will convert empty strings to null values.  I had to put the following attribute in each BoundField: ConvertEmptyStringToNull="False".  Whew!

No comments:

Post a Comment