SIGN UP MEMBER LOGIN:    
ARTICLE

Showing Category and Subcategory Using Nested Repeater in ASP.NET

Posted by Rohatash Kumar Articles | ASP.NET Programming February 15, 2012
This article shows you how to implement nested repeaters and also display category and subcategory using a nested repeater.
Reader Level:
Download Files:
 

This article shows you how to implement nested repeaters and also display category and subcategory using a nested repeater. You create two tables, one for category and another for subcategory and also create a stored procedure for selecting category and sub category from both tables in SQL Server. You have to create a web site and add a new page to the website. Drag and drop two Repeater controls on the form; one is to bind category and the other is for subcategory.  Let's take a look at a practical example. We create tables for category and subcategory.

Creating Table in SQL Server Database

Now create two tables named MajorCategory and MinorCategory. We create CategoryID in MajorCategory table that is the foreign key for the MinorCategory also set the identity property of the CategoryID. The table looks as below.

MajorCategory Table

mg1.gif

Now insert data into the table.

mg2.gif

MinorCategory Table

mg3.gif

Now insert data into the table.

mg4.gif

Creating a Stored Procedure

Now create a stored procedure to select data from both tables.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

ALTER PROCEDURE [dbo].[usp_GetProductsForCategories]

 

AS

SELECT * FROM MajorCategory WHERE CategoryID IN

( SELECT CategoryID FROM MinorCategory )

SELECT p.MinorCategoryId , p.SubCategoryName ,p.CategoryID FROM MinorCategory p

First you have to create a web site.

  • Go to Visual Studio 2010
  • New-> Select a website application
  • Click OK

image1.gif

Now add a new page to the website.

  • Go to the Solution Explorer
  • Right Click on the Project name
  • Select add new item
  • Add new web page and give it a name
  • Click OK

image2.gif

Now create a new website and drag and drop two repeater controls onto the aspx page. The repeater code looks like this.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="categorySubcategory.aspx.cs"

    Inherits="categorySubcategory" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <ul>

        <asp:Repeater ID="outerRep" runat="server" OnItemDataBound="outerRep_ItemDataBound">

            <ItemTemplate>

                <li>

                    <asp:Label Font-Size="Large" Font-Bold="true" ID="lblCategoryName" runat="server"

                        Text='<%# Eval("CategoryName") %>' />

                </li>

                <ul>

                <asp:Repeater ID="innerRep" runat="server">

                    <ItemTemplate>

                        <li style="background-color: AliceBlue">

                            <asp:HyperLink ID="hlProductName" runat="server" Text='<%# Eval("SubCategoryName")%>' />

                      </li>

                    </ItemTemplate>

                </asp:Repeater>

                </ul>

                </ItemTemplate>

                </asp:Repeater>

                </ul>

    </div> </form>

</body>

</html>

 

Now add the following namespaces.

using System.Data.SqlClient;

using System.Data;

 

Now write the connection string to connect to the database.

 

string strConnection = "Data Source=.; uid=sa; pwd=wintellect;database=registration;";

 

Now double-click on the page and write the following code for binding the data with the Repeater.

 

private void BindData()

    {

        SqlConnection myConnection = new SqlConnection("Data Source=.; uid=sa; pwd=wintellect;database=registration;");

        SqlCommand myCommand = new SqlCommand("usp_GetProductsForCategories", myConnection);

        myCommand.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ad = new SqlDataAdapter(myCommand);

        DataSet ds = new DataSet();

        ad.Fill(ds);

        // Attach the relationship to the dataSet

        ds.Relations.Add(new DataRelation("CategoriesRelation", ds.Tables[0].Columns["CategoryID"],

        ds.Tables[1].Columns["CategoryID"]));

        outerRep.DataSource = ds.Tables[0];

        outerRep.DataBind();

    }

Now write the below code on the OnItemDataBound event of the repeater.

protected void outerRep_ItemDataBound(object sender, RepeaterItemEventArgs e)

    {

        if (e.Item.ItemType == ListItemType.Item ||

        e.Item.ItemType == ListItemType.AlternatingItem)

        {

            DataRowView drv = e.Item.DataItem as DataRowView;

            Repeater innerRep = e.Item.FindControl("innerRep") as Repeater;

            innerRep.DataSource = drv.CreateChildView("CategoriesRelation");

            innerRep.DataBind();

        }

    }

 

In Codebehind write the following code like this. 

Codebehind

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

 

public partial class categorySubcategory : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        BindData();

    }

    private void BindData()

    {

        SqlConnection myConnection = new SqlConnection("Data Source=.; uid=sa; pwd=wintellect;database=registration;");

        SqlCommand myCommand = new SqlCommand("usp_GetProductsForCategories", myConnection);

        myCommand.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ad = new SqlDataAdapter(myCommand);

        DataSet ds = new DataSet();

        ad.Fill(ds);

        // Attach the relationship to the dataSet

        ds.Relations.Add(new DataRelation("CategoriesRelation", ds.Tables[0].Columns["CategoryID"],

        ds.Tables[1].Columns["CategoryID"]));

        outerRep.DataSource = ds.Tables[0];

        outerRep.DataBind();

 

    }

    protected void outerRep_ItemDataBound(object sender, RepeaterItemEventArgs e)

    {

 

        if (e.Item.ItemType == ListItemType.Item ||

        e.Item.ItemType == ListItemType.AlternatingItem)

        {

            DataRowView drv = e.Item.DataItem as DataRowView;

            Repeater innerRep = e.Item.FindControl("innerRep") as Repeater;

            innerRep.DataSource = drv.CreateChildView("CategoriesRelation");

            innerRep.DataBind();

        }

    }

}

Now run the application and test it.

mg5.gif

The above output displays subcategory according to the category.

Some Helpful Resources

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks a lot for your clear and easy to understand article.

Posted by Serno Totem May 18, 2012

Gud way to represent the concept !! keep posting more ! Thanks for your contribution !

Posted by Deepak Dwij Apr 08, 2012
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Become a Sponsor