Write Your Own Provider For the ASP.NET DataGrid : Page 2

The ASP.NET DataGrid is a very powerful control, capable of displaying anything that can be represented in tabular format. Find out how you can use it more effectively by creating custom data providers to populate your grids.

by Hasmet Akgun

Oct 21, 2002

Page 2 of 3

Putting Theory into Practice
Here's a practical example. The problem is: How can you display this XML structure in a table on a web page?

Well, you can always use the good old System.Data namespace. Yet, why use a library primarily intended for SQL to deal with XML? Try a whole new approach. Chances are, you will find it simpler and more intuitive.

You can start with the structure that will provide column information to the grid. As mentioned in the preceding section, all you need is a bare-bones class that exposes the columns through its properties. This class will receive the values for all its properties through its constructor, and will store them in private member variables until its public properties are queried by the grid.

Because this class implements both IEnumerable and IEnumerator, the GetEnumerator() method just returns the object itself. Under more complex circumstances, you may want to put the enumeration logic in a separate class, but for the time being, this approach will suffice.

IEnumerator is where you perform the real act. Note how you return false after the final element in MoveNext(), signaling the grid to stop enumeration after that point. Also, any exception occurring within Current() is almost certainly due to a buggy client that has disregarded the return value from MoveNext(), so you can safely raise the InvalidOperationException.

Voila! As the screenshot shows, when you make the DataGrid happy, it returns the favor by shielding you from the complexities of HTML tables, and helps you keep presentation logic separate from data access logic.

Even this relatively simple example shows obvious benefits compared to using the DataView object from the System.Data namespace. Your custom provider entirely encapsulates the data you want to present, so the grid has no idea where the data is coming from, resulting in flexibility. You can change the physical source of your XML without having to touch the presentation logic. You need only modify your provider to fit the source, and the page will work seamlessly.