Nested Datalist example in asp.net using C# and VB.net - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

Nested Datalist example in asp.net using C# and VB.net

In this article I am going to explain how to build a nested datalist (datalist inside datalist) in asp.net.


Description:
To implement this requirement I am using two datalist controls with expand and collapse functionality. I will bind the parent datalist with category and child datalist with sub-category that will be displayed when the expand icon is clicked .
I have created two tables Tb_Category and Tb_Subcategory.

 Nested Datalist example in asp.net using C# and VB.net

Implementation:
Add the webform to project. Drag and drop the require control from toolbox to webform.
  <asp:DataList ID="dlcategory" runat="server" onitemdatabound="DataList1_ItemDataBound" DataKeyField="id">
        <ItemTemplate>
        <img alt = "" style="cursor: pointer" src="images/plus.png" />           
                  <%# DataBinder.Eval(Container.DataItem, "Category")%>
                 <div Style="display: none">
                    <asp:DataList ID="dlsubcategory" runat="server" >
                        <ItemTemplate>
                              <asp:HyperLink runat="server" Text='<%# Eval("SubCategory") %>' CssClass="subcategory"  NavigateUrl="#"></asp:HyperLink>
                        </ItemTemplate>
                    </asp:DataList>
                   </div>
        </ItemTemplate>
        </asp:DataList>

Add the script and style before closing the head section
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>
<style>
.subcategory
{margin-left: 20px;}
a {text-decoration: none;}
</style>

Complete HTML Markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>
<style>
.subcategory
{margin-left: 20px;}
a {text-decoration: none;}
</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList ID="dlcategory" runat="server" onitemdatabound="DataList1_ItemDataBound" DataKeyField="id">
        <ItemTemplate>
        <img alt = "" style="cursor: pointer" src="images/plus.png" />           
                  <%# DataBinder.Eval(Container.DataItem, "Category")%>
                 <div Style="display: none">
                    <asp:DataList ID="dlsubcategory" runat="server" >
                        <ItemTemplate>
                              <asp:HyperLink runat="server" Text='<%# Eval("SubCategory") %>' CssClass="subcategory"  NavigateUrl="#"></asp:HyperLink>
                        </ItemTemplate>
                    </asp:DataList>
                   </div>
        </ItemTemplate>
        </asp:DataList>
    </div>
    </form>
</body>
</html>

Import the namespaces
C# code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.net code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Create sqlconnection
C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

VB.net code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())


Bind the category to parent datalist
Create a method to bind the datalist and call the method in page load.
C# code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindMenu();
        }
    }

public void BindMenu()
    {
        SqlDataAdapter adp = new SqlDataAdapter("Select * from Tb_Category", con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        dlcategory.DataSource = dt;
        dlcategory.DataBind();
    }

VB.net code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindMenu()
        End If
    End Sub

Public Sub BindMenu()
        Dim adp As New SqlDataAdapter("Select * from Tb_Category", con)
        Dim dt As New DataTable()
        adp.Fill(dt)
        dlcategory.DataSource = dt
        dlcategory.DataBind()
    End Sub

Bind the subcategory to child datalist
On ItemDatabound event of parent datalist write the below given code. Search the child datalist and get the records (sub category).
C# code:
protected void dlcategory_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        int id = Convert.ToInt32(dlcategory.DataKeys[e.Item.ItemIndex].ToString());
        SqlCommand cmd = new SqlCommand("Select * from Tb_Subcategory where CategoryId_FK = @id",con);
        cmd.Parameters.AddWithValue("@id", id);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        DataList dlsubcat = (DataList)e.Item.FindControl("dlsubcategory");
        dlsubcat.DataSource = dt;
        dlsubcat.DataBind();        
    }

VB.net code:
Protected Sub dlcategory_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlcategory.ItemDataBound
        Dim id As Integer = Convert.ToInt32(dlcategory.DataKeys(e.Item.ItemIndex).ToString())
        Dim cmd As New SqlCommand("Select * from Tb_Subcategory where CategoryId_FK = @id", con)
        cmd.Parameters.AddWithValue("@id", id)
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        Dim adp As New SqlDataAdapter(cmd)
        Dim dt As New DataTable()
        adp.Fill(dt)
        Dim dlsubcat As DataList = DirectCast(e.Item.FindControl("dlsubcategory"), DataList)
        dlsubcat.DataSource = dt
        dlsubcat.DataBind()
    End Sub

Build, run the project and test it.

 DEMO:
Nested Datalist example in asp.net using C# and VB.net
     In this article we have learn how to build nested Datalist in asp.net using  C# and VB.net. I hope you enjoyed this article. Please post you comment, query and feedback about this article. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.  

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon