Using DataList to List Category/Subcategory with expand - collapse facility via javascript

In this article we will cover how to use the datalist asp.net control for listing your menu with category/ subcategory. It will also allow you to expand and collapse your category / subcategory using javsacript. We will discuss how to use datalist view inside itemtemplate of datalist

In this article we cover how to use the datalist asp.net control for listing your menu with category/ subcategory. It will also allow you to expand and collapse your category / subcategory using javsacript. I am going to teach you to use datalist view inside itemtemplate of datalist


As I have searched on internet developers are facing some difficulties and there is no such kind of example which explains the same. So I thought this article will good help developers.

So here I will use simple table with following attributes for explaining this article.

Cat_id (int),
Cat_name (varchar),
Sub_cat_id (int)


Now in this situation I am just using single table. You can use two table called category and sub_category. I’ll put null entry in sub_cat_id column for main category and rest of them will filled up by their main category.

For implementing above thing create new website as follow.


Visual Studio >> File >> New >> Website >>ASP.NET Website




Then we are supposed to add new database from solution explorer in our website and then add new table as following screenshot




After successfully creation of new table just makes some data entry as following screenshot.


Now add new WebForm from solution explorer name it menu.aspx as follow.



Now first of all drag drop <asp:datalist> control from toolbox under DATA tab then go to source of page it will look like as follow.

<asp:DataList ID="DataList1" runat="server">
</asp:DataList>

After this we are going to bind our main category, for that add following code inside the itemtemplate of datalist control

<ItemTemplate>
<asp:Label ID="id" runat="server" Text='<%# Eval("cat_id") %>' Visible="false"></asp:Label>
<asp:HyperLink ID="MainCat" Text='<%# Eval("cat_name") %>' runat="server" NavigateUrl="#"></asp:HyperLink>
</ItemTemplate>


In above code Label control is used to store the id of main category which is visible false to the user so he/she will not be able to see id. I have set text property using Eval functionality of asp.net. In Hyperlink I set navigatUrl property to “#” because we do not need to redirect page on main category click.

So now we’ll add another datalist control of asp.net inside itemtemplate for displaying subcategory of main category. We are also going to collapse and expand the main category so make sure you put another datalist in <asp:panel></asp:panel> tag as follow:

<asp:Panel ID="panelsubcat" runat="server" style="display:none;">
<asp:DataList ID="subcat" runat="server">
<ItemTemplate>
<asp:LinkButton ID="subcat" Text='<%# Eval("cat_name") %>' runat="server"
PostBackUrl='<%# Eval("cat_id","~/ViewCatagory.aspx?Cat={0}") %>'></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</asp:Panel>



Inside itemtemplate of second datalist I have put linkbutton and set two property one is text another is postbackurl to redirect user for their respective category. We are passing the categoryid using querystring functionality of asp.net so on another page you can use this category id from query string. After this phase your .aspx code and design will look like as follow.




Now we are going to write our c# code. Firstly add following code on page load event which get all the main category.

SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;
        con.ConnectionString =@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
        con.Open();
        cmd.CommandText = "select * from category where sub_cat_id is Null";
        cmd.Connection = con;
        dr = cmd.ExecuteReader();
        DataList1.DataSource = dr;
        DataList1.DataBind();

Now run your website and you’ll able to see your main category in the browser.

To display a subcategory we are suppose to bind our second datalist control which we have put inside itemtemplate of the first datalist. For this we are going to write our code in ItemDataBound event of first datalist. So paste following code inside the ItemdataBound event.

Panel p = (Panel)e.Item.FindControl("panelsubcat"); //Find panel
        HyperLink l = (HyperLink)e.Item.FindControl("MainCat"); //Get Main category
        l.Attributes.Add("onclick", "showsubmenu('" + p.ClientID + "')");
        Label id=(Label)e.Item.FindControl("ID"); //Find main category id
        int catid = Convert.ToInt16(id.Text.ToString());
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;
        con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
        con.Open();
        cmd.CommandText = "select * from category where sub_cat_id="+catid;
        cmd.Connection = con;
        dr = cmd.ExecuteReader();
        DataList d = (DataList)e.Item.FindControl("subcat"); //Find another gridview
        d.DataSource = dr;//Set datasorue
        d.DataBind();         


In above code we are binding our subcategory datalist control. Explanation for above code line by line

1) Find panel from the first datalist itemtemplate
Panel p = (Panel)e.Item.FindControl("panelsubcat");  //Find panel

2) Find Main category hyperlink to perform collapse and expand facilities
        HyperLink l = (HyperLink)e.Item.FindControl("MainCat"); //Get Main category
3) Add javascript function to each and every Main category link. In argument we are passing client id of panel which contains subcategory datalist.
    l.Attributes.Add("onclick", "showsubmenu('" + p.ClientID + "')");

4) Get main category id to find subcategory by following code
Label id=(Label)e.Item.FindControl("ID"); //Find main category id
        int catid = Convert.ToInt16(id.Text.ToString());

5) Finally fire sql query and bind second datalist.

Now we are done with displaying category and subcategory now our goal is to achieve collapse and expand facility for this we are using javascript go to .aspx page and add following javascript function In <script></script> tag.

<script language="javascript">
        function showsubmenu(id)
        {
            var subcat=document.getElementById(id);
            if(subcat.style.display == 'none')
            {
                subcat.style.display= 'block';
            }
            else
            {
                subcat.style.display= 'none';
             }
             
        }
     </script>

Final output of above example is as follow




Left side of image is showing Main category when you click any of them you can expand subcategory of respective Main category.

Download above example solution from HERE

By Mihir Soni   Popularity  (18970 Views)