Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET Controls » Using Web User Controls in Repeaters and DataList

Using Web User Controls in Repeaters and DataList

This article shows a simple example of how to encapsulate the complexity when using the ASP.Net Repeater and DataList control using a custom web user control.

Page Views : 49943
Downloads : 717
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RepeaterUserControl.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

The ASP.Net data bound DataList and Repeater controls give us the ability to create flexible HTML layouts for tabular and XML hierarchal data. However, when you throw in a need for conditional logic or some string formatting or perhaps the need to edit/update the data, things get complicated fast. 

This complexity is reduced significantly if encapsulated within a custom web user control. We then call this control within the Repeater or DataList.

This article will walk through a simple example of displaying some products by product category. The custom web user control will be used to format the product information and to format the product's price (see figure 1).

Figure 1 - Formatted Output  

Solution Overview

The data that we will use is stored in an XML file. The main web page will use a DataList control nested inside of a DataRepeater control. The Repeater is used to grab the category names, e.g. "Beverages" and the DataList control is used to the grab the product information. This product information is then passed to a web user control for formatting.

Code Walk Through

A sample of the data in XML file is shown in figure 2.

<?xml version="1.0" standalone="yes"?>

<DataSetNorthwind>

  <Categories>

    <CategoryID>1</CategoryID>

    <CategoryName>Beverages</CategoryName>

    <Description>Soft drinks, coffees, teas, beers, and ales</Description>

    <Products>

      <ProductID>1</ProductID>

      <ProductName>Chai</ProductName>

      <SupplierID>1</SupplierID>

      <CategoryID>1</CategoryID>

      <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit>

      <UnitPrice>18</UnitPrice>

      <UnitsInStock>39</UnitsInStock>

      <UnitsOnOrder>0</UnitsOnOrder>

      <ReorderLevel>10</ReorderLevel>

      <Discontinued>false</Discontinued>

    </Products>

    <Products>

      <ProductID>2</ProductID>

      <ProductName>Chang</ProductName>

      <SupplierID>1</SupplierID>

      <CategoryID>1</CategoryID>

      <QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>

      <UnitPrice>19</UnitPrice>

      <UnitsInStock>17</UnitsInStock>

      <UnitsOnOrder>40</UnitsOnOrder>

      <ReorderLevel>25</ReorderLevel>

      <Discontinued>false</Discontinued>
    </Products>

Figure 2 - Sample of the XML Data

Figure 3 show all of the code used for the main page; there is no code behind used.

<%@ Page Language="C#" %>

<%@ Register Src="Product.ascx" TagName="Product" TagPrefix="uc1" %>

<!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>Product Information</title>

</head>

<body>

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

    <div> 

        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="XmlDataSource1">

        <ItemTemplate><br />

            <H1><%# XPath("CategoryName")%></H1>

            <hr />           

            <asp:DataList ID="DataList1" runat="server" RepeatColumns=2

              DataSource='<%# XPathSelect("Products") %>'  >

                <ItemTemplate>

                    <uc1:Product ID="Product1" runat="server" ProductName=<%# XPath("ProductName")%>

                      Quantity=<%# XPath("QuantityPerUnit")%> Price=<%# XPath("UnitPrice")%> />

                </ItemTemplate>

            </asp:DataList>         

        </ItemTemplate>

        </asp:Repeater>       

        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Products.xml"

          XPath="DataSetNorthwind/Categories">

        </asp:XmlDataSource>

        &nbsp;</div>     

    </form>

</body>
</html>

Figure 3 - Code For Main Page

Note that no code behind was used for the example. The XML file is loaded by the "XmlDataSource" control. 

To use a web user control one first registers it with the statement:

<%@ Register Src="Product.ascx" TagName="Product" TagPrefix="uc1" %>

Next we use the web user control in this statement:

<uc1:Product ID="Product1" runat="server" ProductName=<%# XPath("ProductName")%> Quantity=<%# XPath("QuantityPerUnit")%> Price=<%# XPath("UnitPrice")%> />

The control's attributes are the public properties that are implemented in the customized web user control.

As you can see the code above is not cluttered up with alot of html formatting. The web user control will handle this part.

Figure 4 shows the html of the web user control. Note the use of div to format it and the server side label control to display the data.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Product.ascx.cs" Inherits="Product" %>

&nbsp;

<br />

<div style="padding:5px 0px 0px 10px">

<div style="z-index: 101; left: 4px; width: 438px; position: relative; top: 3px;

    height: 22px; background-color: #0099cc;">

    &nbsp;

<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Larger" Text="Product Name: "

    Width="128px"></asp:Label>

<asp:Label ID="LabelProductName" runat="server" Text="Label" Width="225px"></asp:Label></div>

<div style="z-index: 102; left: 4px; width: 438px; position: relative; top: 9px;

    height: 100px; background-color: #33ccff">

    <div style="z-index: 101; left: 11px; width: 414px; position: relative; top: 13px;

        height: 79px; background-color: #330099">

        <asp:Label ID="Label2" runat="server" Font-Size="Larger" ForeColor="White" Style="text-align:right; left: 24px;

            position: relative; top: 11px" Text="Quantity Per Unit:" Width="157px"></asp:Label>

        <asp:Label ID="Label4" runat="server" Font-Size="Larger" ForeColor="White" Style="text-align:right;left: -137px;

            position: relative; top: 39px" Text="Unit Price:" Width="157px"></asp:Label>

        <asp:Label ID="LabelQuantity" runat="server" Font-Size="Larger" ForeColor="White" Style="left: 192px;

            position: relative; top: -9px" Text="Label" Width="214px"></asp:Label>

        <asp:Label ID="LabelUnitPrice" runat="server" Font-Size="Larger" ForeColor="White" Style="left: -26px;

            position: relative; top: 20px" Text="Label" Width="75px"></asp:Label></div>

    </div>
</div>

Figure 4 - HTML For Web User Control

Any conditional logic or formatting the data is normally performed by the code behind. Figure 5 shows the code behind of the user web control:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class Product : System.Web.UI.UserControl

{

    private string _productName;

    public string ProductName

    {

        get { return _productName; }

        set { _productName = value; }

    }

 

    private string _quantity;

    public string Quantity

    {

        get { return _quantity; }

        set { _quantity = value; }

    }

 

    private string _price;

    public string Price

    {

        get { return string.Format("{0:C}",decimal.Parse(_price)); }

        set { _price = value; }

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

        this.PreRender += new EventHandler(Product_PreRender);

    }

 

    void Product_PreRender(object sender, EventArgs e)

    {

        LabelProductName.Text = ProductName;

        LabelQuantity.Text = Quantity;

        LabelUnitPrice.Text = Price;

    }
}

Figure 5 - Code Behind For User Web Control

It's worth noting again that the public properties are available as html attributes when using the control from the main web form. You can see we format the price before we display it. We could have also place conditional logic here as well. As a more complex case, we could have supported editing of this data. This wouldn't make sense for our static XML data file but might for a SQL database source, depending on its application.

Conclusion

This article shows a simple example of how to encapsulate the complexity when using the ASP.Net Repeater and DataList control using a custom web user control.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Author
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Where's the files by Aaron On January 11, 2008
Hi I downloaded the files and there is only 2 files in the zip. RepeaterUserControl.sln and RepeaterUserControl.suo Any chance you can upload it again. Thanks Aaron
Reply | Email | Modify 
Re: Where's the files by Mike On January 27, 2008

Wow, thanks for pointing that out.  Can't believe it took so long for someone to point that out.  I added the missing files.  After opening the directory in the development environment, set the Products.aspx as the start page and it should run fine now.

Mike

Reply | Email | Modify 
thank you by Zaid On March 6, 2008
Dear Mike, thanks alot for such helpful explnation for junior developer :) just one question: i have a huge database and when i use the repeater to bring the title for example, it retrive a whole list! i want only 10 for example to show in my page ... any help how i can do that? thanks for such article again
Reply | Email | Modify 
binding repeater with list containing usercontrols by James On August 11, 2009
Hi Mike:

Thank you very much for the posting. I have been trying to figure out how to add user controls and your posting helped me to get the initial work completed. Now comes the hard part. .... I can seem to get the binded values to display. I have also created a posting on asp.net. We wondering if you could kindly advice.

http://forums.asp.net/p/1457825/3342190.aspx#3342190

thanks a million,
TWnzUS
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.