Tuesday, August 31, 2010

How to bind DataTable to a asp.net menu using ParentID and ID relationship

Here are some useful tips for you:
  1. Menu control expects a heirarchical data structure, so we cant bind the DataTable to menu directly.
  2. Use data table Select where ParentID = ID
  3. Please use a recursive method to create child items relevent to current menu item ID
Here is an example that you may use to transfer your ralational data structure (TABLE) to hierarchical data structure (TREE) using the relationship between ParentID and ID
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsPostBack)
                this.AddItems(this.menuNavigation.Items, 0, this.LoadData());
        }
        private void AddItems(MenuItemCollection items, int level, System.Data.DataTable dt)
        {
            string filterExp = string.Format("ParentID='{0}'", level);
            foreach (System.Data.DataRow r in dt.Select(filterExp))
            {
                MenuItem item = new MenuItem()
                {
                    Text = r[1].ToString(),
                    NavigateUrl = r[2].ToString()
                };
                this.AddItems(item.ChildItems, int.Parse(r[0].ToString()), dt);
                items.Add(item);
            }
        }
        private System.Data.DataTable LoadData()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("ID"String.Empty.GetType());
            dt.Columns.Add("[Name]"String.Empty.GetType());
            dt.Columns.Add("[Link]"String.Empty.GetType());
            dt.Columns.Add("ParentID"String.Empty.GetType());
            dt.Columns.Add("[Order]"String.Empty.GetType());
            int index = 9;
            for (int i = 0; i < 1100; i++)
            {
                string item = "{0},Item{1},Page{1}.aspx,{2},{1}";
                if (i < 110)
                {
                    index = i < 10 ? 0 : int.Parse(Math.Ceiling((decimal)i / 10).ToString());
                    dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
                }
                else
                {
                    if (i % 10 == 0) index++;
                    dt.Rows.Add((string.Format(item, i + 1, i, index)).Split(char.Parse(",")));
                }
            }
            return dt;
 
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu runat="server" ID="menuNavigation" />
    </form>
</body>
</html>

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...