Thursday, 5 July 2007

SubSonic GridView and ObjectDataSource

I have been experimenting with using SubSonic to convert my commentaries web page from PHP to ASP.NET. This is a very simple web page allows you to look at a list of books, sort them and filter them - nothing complicated. And Subsonic offers an automatic DAL layer which requires you simply to point it at your database and let it create the classes for you.

So one of the first tasks I approached was to work out how to get a asp:GridView to work with my SubSonic data objects. My first approach was to do it in code, with the following code in my Page_Load event:

CommentaryController c = new CommentaryController();
CommentaryCollection cc = c.FetchAll();            
gridCommentaries.DataSource = cc;
gridCommentaries.DataBind();

This worked nicely, but I wanted to know if there was a better way using the asp:ObjectDataSource. The SubSonic documentation is still a little sparse in this area, but I eventually worked out the syntax. You use the auto-generated "Controller" object that SubSonic has made for your table:

<asp:ObjectDataSource ID="odsCommentaries" runat="server" 
TypeName="CommentariesDB.CommentaryController"
SelectMethod="FetchAll" />

Simple when you know how! Now you just need to set the DataSourceID of the grid. Paging can be also turned on, but sorting doesn't. I'll perhaps post again when I have gone a bit deeper.

Post a Comment