DataGrids, Custom columns and Paging

I had a co-worker who presented a problem today. It was around adding paging to a datagrid (grrr Microsoft for making us do all the work!) and the fact that he had added what looked right, but the grid wasn't rendering on the page change. I went through the typical scenario of setting up paging by adding the Page Index Change event handler then, nothing. Something wasn't right and I surmised that the problem was that he had gone through a few iterations of getting the paging going and taking various approaches (hand coding the event handler, adding it to the web.config, etc.) so my conclusion was that the DataGrid, the code behind, and the aspx page were out of whack somehow. I wasn't happy suggesting the "black magic" approach to rebuilding the DataGrid with a duplicate one on the page (or creating it from scratch again) just because there had to be an easier solution.

Tonight I built a small spike project to test out what was happening. A couple of people have experienced pain and suffering in the past with the DataGrid and how events would just vanish and not fire. One thing I noted in his code was that he had a DataGrid on the page but was then building columns on the fly (to do some custom work with the columns and linking them to subsequent pages). Once I had my spike project up and running, I turned off the auto-generated columns and fed it the datasource (a quick object with a few public properties). Everything was still fine. The problem arose when I added this:

BoundColumn datagridcol = new BoundColumn();
datagridcol.HeaderText = "ID";
datagridcol.DataField = "Id";

I've used this method before but usually when I created a DataGrid completely from scratch and added it to the page controls manually. In my spike project after adding this code, the DataGrid vanished completely. So the question here is this a supported design? Building columns on the fly with a DataGrid control already on the page? Or is this a hybrid that isn't supported (or recommended)? Another interesting thing to note. I now can't get to my event handlers in the Property tab in Visual Studio anymore. The lightning bolt just isn't there now. Hmmm.

I did find a bit of a solution. I added the following to the DataGrid in the aspx page to fix it:

<asp:BoundColumn Visible=False></asp:BoundColumn>

Now the paging works and everything shows up.

No Comments