title: Display complete list of categories and subcategories using Repeater
body: <p>I have successfully displayed the list of categories and their corresponding sub categories using nested Repeater controls:</p>
  
  <p><strong>.aspx</strong></p>
  
  <pre><code>&lt;asp:Repeater ID="rMainCategories" runat="server" OnItemDataBound="rMainCategories_ItemDataBound"&gt;
      &lt;ItemTemplate&gt;
          &lt;li&gt;
              &lt;asp:Label ID="lblCategoryName" runat="server"
                  Text='&lt;%# Eval("MainCategory") %&gt;' /&gt;
          &lt;/li&gt;
          &lt;ul&gt;
              &lt;asp:Repeater ID="rSubCategories" runat="server"&gt;
                  &lt;ItemTemplate&gt;
                      &lt;li&gt;
                          &lt;asp:HyperLink ID="hlProductName" runat="server" Text='&lt;%# Eval("SubCategory")%&gt;' /&gt;
                      &lt;/li&gt;
                  &lt;/ItemTemplate&gt;
              &lt;/asp:Repeater&gt;
          &lt;/ul&gt;
      &lt;/ItemTemplate&gt;
  &lt;/asp:Repeater&gt;
  </code></pre>
  
  <p><strong>.aspx.cs</strong></p>
  
  <pre><code>void GetCategories()
  {
      con.Open();
      SqlCommand cmd = new SqlCommand();
      cmd.Connection = con;
      cmd.CommandText = "SELECT m.MainCatID, m.Category AS MainCategory " +
          "FROM MainCategories m WHERE m.MainCatID " +
          "IN (SELECT MainCatID FROM SubCategories) " +
          "SELECT s.SubCatID, s.Category AS SubCategory, s.MainCatID FROM SubCategories s";
      SqlDataAdapter da = new SqlDataAdapter(cmd);
      DataSet ds = new DataSet();
      da.Fill(ds);
  
      ds.Relations.Add(new DataRelation("CategoriesRelation", ds.Tables[0].Columns["MainCatID"],
          ds.Tables[1].Columns["MainCatID"]));
      rMainCategories.DataSource = ds.Tables[0];
      rMainCategories.DataBind();
      con.Close();
  }
  
  protected void rMainCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
  {
      if (e.Item.ItemType == ListItemType.Item ||
      e.Item.ItemType == ListItemType.AlternatingItem)
      {
          DataRowView drv = e.Item.DataItem as DataRowView;
          Repeater rSubCategories = e.Item.FindControl("rSubCategories") as Repeater;
          rSubCategories.DataSource = drv.CreateChildView("CategoriesRelation");
          rSubCategories.DataBind();
      }
  }
  </code></pre>
  
  <p><strong>Output</strong></p>
  
  <p><img src="https://i.stack.imgur.com/rDXYv.png" alt="list of main categories with sub categories"></p>
  
  <p><strong>List of Main Categories</strong></p>
  
  <p><img src="https://i.stack.imgur.com/bAbU7.png" alt="list of main categories"></p>
  
  <p>Is there a way I can also display categories without sub categories?
  Please advise. Thank you.</p>