Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

How To Create Multi Level Menu Dynamically Using C# in ASP.Net

, 24 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Friends, This is Part 4 of the series “Creating Menus”. We have already seen how to create a single level menu dynamically in ASP.Net here. This post will explain how to create a multi-level menu dynamically using C# in Asp.Net. You can also read the other 2 posts in this series with the links menti

Friends,

This is Part 4 of the series “Creating Menus”. We have already seen how to create a single level menu dynamically in ASP.Net here. This post will explain how to create a multi-level menu dynamically using C# in Asp.Net. You can also read the other 2 posts in this series with the links mentioned below –

To begin with, we will make some changes to our Categories table in our database to hold Parent and child relationships between the menus.  We added a ParentCategoryID in our table that will store the Parent CategoryID of the menu present in record. For parent categories, vlue in this column equals Zero. Now, the table structure looks something like below-

dynamic-multi-level-menu-1

After the structure is defined, its time to fill in with some dummy data. Lets assume we have the below data.

dynamic-multi-level-menu-2

Our DB is defined. Time to write some code! We make changes to our existing Repeater Control adding a Literal control that will hold all sub menus of parent menu. An important thing to note in this markup is we have handled the “ItemDataBound” event of the Repeater control.

<asp:repeater ID="rptCategories" runat="server" OnItemDataBound="rptCategories_ItemDataBound">
                    <headertemplate>
                        <div class="menu"><ul>
                    </headertemplate>
                    <itemtemplate>
                        <li>
                            <a href='#'>< %#Eval("Name") %></a>
                            <asp:literal ID="ltrlSubMenu" runat="server"></asp:literal>
                        </li>
                    </itemtemplate>
                <footertemplate>
                       </ul></div>
                </footertemplate>
                </asp:repeater>

In the code file (.master.cs/.aspx.cs/.acsx.cs), we will make a call to our database to get all the categories and bind the data to the repeater control.  For doing this, we will write the below code.

        DataTable allCategories=new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCategories();
            }
        }
        private void LoadCategories()
        {
            allCategories = GetAllCategories();
            rptCategories.DataSource = GetCategories();
            rptCategories.DataBind();
        }
        private DataTable GetCategories()
        {
        SqlConnection connection = new SqlConnection("Data Source=NITESH;Initial Catalog=TestDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient");
        SqlCommand selectCommand = new SqlCommand("SELECT ID,CategoryName FROM Categories WHERE ParentCategoryID=0", connection);
        DataTable dt = new DataTable();
        try
        {
            connection.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();
            if (reader.HasRows)
            {
                dt.Load(reader);
            }
            reader.Close();
        }
        catch (SqlException)
        {
            throw;
        }
        finally
        {
            connection.Close();
        }
        return dt;
        }
        private DataTable GetAllCategories()
        {
        SqlConnection connection = new SqlConnection("Data Source=NITESH;Initial Catalog=TestDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient");
        SqlCommand selectCommand = new SqlCommand("SELECT ID,CategoryName FROM Categories", connection);
        DataTable dt = new DataTable();
        try
        {
            connection.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();
            if (reader.HasRows)
            {
                dt.Load(reader);
            }
            reader.Close();
        }
        catch (SqlException)
        {
            throw;
        }
        finally
        {
            connection.Close();
        }
        return dt;
        }
        protected void Categories_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
            {
                if (allCategories != null)
                {
                    DataRowView drv = e.Item.DataItem as DataRowView;
                    string ID = drv["ID"].ToString();
                    DataRow[] rows = allCategories.Select("ParentCategoryID=" + ID, "Name");
                    if (rows.Length > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("<ul>");
                        foreach (var item in rows)
                        {
                            sb.Append("<li><a href='#'>" + item["CategoryName"] + "</a></li>");
                        }
                        sb.Append("</ul>");
                        (e.Item.FindControl("ltrlSubMenu") as Literal).Text = sb.ToString();
                    }
                }
            }
        }

If you see the code above, most of the code is similar to our previous post. So, I will explain the remaining part in this post. 1st of all we are binding only parent categories to the Repeater control in GetCategories(). Secondly, we get all categories in a separate DataTable (lets call it Main DT for this post in future references) which we will use in the rptCategories_ItemDataBound() event handler. Inside the event handler, we check if the current item is a valid Item(while binding Repeater control fires this event for binding header and footer rows as well). If yes, we get the ID of the current record and filter our main DT where ParentCategoryID = ID of the current record so that we have all child categories for the current menu. Once filtered, we create a dynamic HTML string using <ul> and <li> tags and finally assign this text to the Literal control defined in our .aspx page.

At this point, you’re done with your main coding part and as always you need to apply CSS to the menus. Add the below CSS to your .css file and execute the application.

.menu{
    width: 500px;
    margin: 0px auto;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    font-size: 14px;
}
.menu ul li a:link, div ul li a:visited {
    display: block;
    background-color: #f1f1f1;color:#000;
    text-align: center;
    text-decoration: none;
    padding: 4px;
    border-bottom: 1px solid #fff;
    width: 150px;
}
.menu ul li a:hover{
    background-color: #ccc;
}
.menu ul li ul li a:link, li ul li a:visited {
    display: block;
    background-color: #f1f1f1;
    color: #000;
    text-align: center;
    text-decoration: none;
    padding: 4px;
    border-bottom: 1px solid #fff;
    width: 150px;
}
.menu ul li ul li a:hover {
    background-color: #ccc;
}
.menu ul {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
}
.menu ul li {
    float: left;
    margin-left: 5px;
}
.menu ul li ul li {
    float: none;
    margin-left: 0px;
}
.menu ul li ul {
    display: none;
}
.menu li:hover ul{
    display: block;
}

You will see the output something like below.

dynamic-multi-level-menu-3

Hope you like this post! Keep learning and sharing folks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nitesh Luharuka
Team Leader Independent IT Professional, Consultant
India India
An Independent IT Professional and Consultant on MS Technologies like .Net | MVC | Silverlight | Sharepoint | MS Project Server along with open source CMS Systems like DotNetNuke etc.
 
I am an enthusiastic technocrat who love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionWant to create a 2nd level menu.. [modified] PinmemberMember 1115919411-Nov-14 3:55 
AnswerRe: Want to create a 2nd level menu.. PinmemberNitesh Luharuka11-Nov-14 17:31 
GeneralRe: Want to create a 2nd level menu.. PinmemberMember 1115919411-Nov-14 18:28 
GeneralRe: Want to create a 2nd level menu.. PinmemberNitesh Luharuka11-Nov-14 20:05 
GeneralRe: Want to create a 2nd level menu.. Pinmemberahmed2071-Feb-15 21:33 
GeneralRe: Want to create a 2nd level menu.. PinmemberNitesh Luharuka1-Feb-15 21:41 
GeneralGood stuff PinmemberGaurav.Kumar.Arora27-Oct-14 11:24 
GeneralMy vote of 4 PinprofessionalMB Seifollahi26-Jul-14 2:32 
GeneralRe: My vote of 4 PinmemberNitesh Luharuka26-Jul-14 3:42 
AnswerRe: My vote of 4 PinprofessionalMB Seifollahi26-Jul-14 5:56 
GeneralRe: My vote of 4 PinmemberNitesh Luharuka27-Jul-14 20:33 
AnswerRe: My vote of 4 PinprofessionalMB Seifollahi28-Jul-14 23:22 
QuestionNeed help debugging PinmemberDannoman123425-Jul-14 6:54 
AnswerRe: Need help debugging PinmemberNitesh Luharuka25-Jul-14 8:56 
QuestionArticle needs a correction PinmemberDannoman123425-Jul-14 6:22 
AnswerRe: Article needs a correction PinmemberNitesh Luharuka25-Jul-14 8:55 
GeneralRe: Article needs a correction PinmemberDannoman123425-Jul-14 8:57 
GeneralRe: Article needs a correction PinmemberNitesh Luharuka25-Jul-14 9:19 
QuestionCSS is not applying to RepeaterControl PinmemberDannoman123424-Jul-14 7:27 
AnswerRe: CSS is not applying to RepeaterControl PinmemberNitesh Luharuka24-Jul-14 8:26 
GeneralRe: CSS is not applying to RepeaterControl PinmemberDannoman123424-Jul-14 9:14 
GeneralRe: CSS is not applying to RepeaterControl PinmemberNitesh Luharuka24-Jul-14 9:23 
GeneralRe: CSS is not applying to RepeaterControl PinmemberDannoman123425-Jul-14 1:48 
GeneralRe: CSS is not applying to RepeaterControl PinmemberDannoman123425-Jul-14 4:19 
GeneralRe: CSS is not applying to RepeaterControl PinmemberNitesh Luharuka25-Jul-14 8:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 24 Jul 2014
Article Copyright 2014 by Nitesh Luharuka
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid