Ayende vs the GridView: Part 1

time to read 4 min | 704 words

I'd a problem in my project today, where I just couldn't figure out how to solve the problem of binding a data grid to a custom list of business objects. I'm certain that there is a lot of info there, but I needed something simple, just take a list of object, and bind them to the grid, based on what I would tell you. I really wanted to keep the nice features of the GridView which allows for rapid proto-typing, so you could declare it like:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
       
<asp:boundfield datafield="Name" headertext="Name In Hebre" />
    </Columns>
</asp:GridView>

As I might have a lot of functionality there, and as I wanted to be able to filter which properties I wanted to display, I was in a bind. I just couldn't get the GridView to dipslay the list property, and I certainly wasn't going to grab the data via a dataset, as most example seem to suggest.

I tried to do something with ObjectDataSource, which was an utter failure. The only examples I could find were how to bind to a freaking dataset or steps in the IDE. I want to see code, not play around with the IDE. After wasting too long on this, I decided that I would just write convert my business objects collection to a datatable and be done with it.

I passionately hate doing any more work than I has to, and I've a lot of business objects there that I would need to convert. I thought about it for a bit, and realized that I already have a mapping of the "interesting" properties of a class, the ones that are persisted to database. Because I already have this knowledge, I can act on it. I mapped the business objects to NHibernate via ActiveRecord. ActiveRecord creates an in memory structure that is used to generate the mapping xml for NHibernate, but there is no reason that I can't take advantage of it to generate a convertor for each object.

The result is about ~200 lines of code that built an object capable of translating a list of object ot a datatable. Total time invested was less than the time that I had researched the ObjectDataSource stuff. The end result looks something like this:

ActiveRecordModel model = ActiveRecordBase.GetModel(typeof(T));
foreach(PropertyModel prop in model.Properties)
{
    adapter.ResgisterColumn(prop.Property);
}
//Assuming a single pk per class

PrimaryKeyModel pk = (PrimaryKeyModel) model.Ids[0];
adapter.RegisterPrimaryKey(pk.Property);