Binding WebHierarchicalDataGrid to IEnumerable

Alex Kartavov / Thursday, April 8, 2010
Hey Guys,
 
There have been a few requests for documentation on how to bind WebHierarchicalDataGrid to a custom collection. In this article I will show you how to do just that. WebHierarchicalDataGrid supports binding to the following data types:
Hierarchical Data Source Controls (XmlDataSource, WebHierarchicalDataSource, SiteMapDataSource)
DataSet
IEnumerable
If you have one of these data types with the correct configuration, WebHierarchicalDataGrid will display the data automatically when bound. In the case of a custom collection that implements the IEnumerable interface, the correct configuration means that the custom objects that makes up the collection must publicly expose an IEnumerable property for the child data.
In the sample I am going to show you, the collection consists of Category objects. Each Category object exposes an IEnumerable property that contains Product data. This sets up the hierarchical relation between the Category and Product data.
The complete sample can be downloaded below.
In C#:
    public class Category
    {
     
        private int categoryID;
        private string categoryName;
        private string description;
        private List<Product> products;
 
      ...
 
        public List<Product> Products
        {
            get
            {
                if (products == null)
                {
                    products = new List<Product>();
                }
 
                return this.products;
            }
        }
 
        #endregion
    }
With the Category collection configured, there are a few things you have to define for WebHierarchicalDataSource:

1)      Set the DataSource property to the collection and databind. Do this on every postback if you are using load on demand for the control.

2)      Set the DataKeyField property to the primary key column of the parent data.

The code looks like this:
In ASPX:
<ig:WebHierarchicalDataGrid ID="WebHierarchicalDataGrid1" runat="server" Height="400px"
            Width="800px" DataKeyFields="CategoryID">
        </ig:WebHierarchicalDataGrid>
In C#:
protected void Page_Load(object sender, EventArgs e)
    {
        this.WebHierarchicalDataGrid1.DataSource = DataUtil.CategoriesAndProducts;
        this.WebHierarchicalDataGrid1.DataBind();
    }
These are the only steps you will need to bind WebHierarchicalDataGrid to a custom collection. Run the sample and the control displays the hierarchical data.
Please feel free to comment on this post and let me know if more complex examples are needed.
BindingWebHierarchicalDataGridtoIEnumerable.zip