Hierarchical results in ASP.NET GridView
Here is one technique that I use in ASP.NET to show hierarchical data like categories tree, sitemaps listing, department/user-levels, etc. A GridView control is used instead of a TreeView control. The method does not require any complex coding and loops; and also does not require any xml file generation. It does, however, require a good stored-procedure (or a db script) to give a sorted resultset.
Lets start with the database table, Categories, which we have like shown below.
CategoryID is the primary key. ParentID is id of parent category, and if zero it is considered to be top level category.

First requirement is to get resultset sorted as per required. Here is a stored procedure code, which will populate the sorted resultset. This code works for three levels of depth of the categories. It can be easily changed to higher levels by adding Sort# column in the temp table and and writing additional INSERT INTO statement. One limitation of the query is that it does not handle infinite depth level.

Here is a sample resultset from the SP script:

Rest of the process in the UI is very simple. A GridView control is used and is databound to the above SP. Also, three CSS classes are required for each three levels. Then all we need to do is to define ItemTemplate of the GridView. CSS and ASPX codes are shown below:


Here is the result page from the above codes.











Very Good Thanks
Ray
March 3, 2008
Great!!
Padam Raj
June 25, 2008