The DataGrid is Dead? Long-live the DataGrid (Part 1 of N)

Published 29 June 05 10:47 AM | despos

I'm writing chapter 10 of "Programming ASP.NET--Fundamentals" entirely dedicated to grids. I split the chapter in two parts--DataGrid and GridView. In the first part, I briefly discuss the main traits of DataGrids and try to compare them to the enhancements brought by the new big brother. In other words, I'm apparently covering the DataGrid control in the book only to show it in a bad light. Apparently? It was a tough decision, actually.

The more I think of it, the more the conclusion appears clear and crystalline. Drop the DataGrid and embrace the GridView--no matter  you're building a new app from scratch or simply adapting an existing one. GridView and DataGrid have nearly the same high-level capabilities, but the GridView has a strong built-in support for data source controls. With DataGrids, you need to be familiar with best practices for paging and sorting, and need to implement them. With GridViews, you still need to be aware of practices but need to write much less code (often, no code at all) and the overall API of the control guides you to write that little code in the best way.

Consider classic paging. In ASP.NET 1.x, you retrieve a DataSet and bind it to DataSource. Next, you enable paging and write a handler for PageIndexChanged. This approach is hardly optimal because it retrieves the whole data set for each and every postback caused by the grid. You need caching. In the end, this means you build an extra layer over your DAL to support ASP.NET caching. In ASP.NET 2.0, if you use the GridView control you can handle of this burden at design-time. If you stick to DataGrids it gets simplified if you employ data source controls.

protected void grid_PageIndexChanged(object sender,
         DataGridPageChangedEventArgs e)
{
    grid.CurrentPageIndex = e.NewPageIndex;

    // Must be repeated to force a refresh
    grid.DataSourceID = "SqlDataSource1";
}

To enable caching, you simply turn on EnableCaching on the SqlDataSource component. Note that you still need to reassign DataSourceID to trigger an internal data source changed event and cause the control to load its new data.

My idea is that DataGrid doesn't really belong to ASP.NET 2.0 but has been reasonably maintained for compatibility, as it is one of the most used controls in ASP.NET 1.x apps. My suggestions go along the following guidelines:

  • Don't touch anything of how it works today if you don't have time/budget for a serious redesign.
  • Don't switch to GridView only to save a few event handlers. Embracing the GridView is a more thoughtful choice; don't use GridView like a DataGrid.
  • If you have time/budget, or if you're building a new app, by all means go with GridViews.
  • To use a GridView at its fullest probably requires you to reconsider the DAL--which is not bad anyway :-)

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)