Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » WebForms 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.

Total page views :  30675
Total downloads :  442
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RepeaterUserControl.zip
 
Become a Sponsor


MindCracker Jobs

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.


Login to add your contents and source code to this article
 About the author
 
Mike Clark
Mike is a software consultant with 10+ development experience who works on IT projects mainly for Microsoft and Boeing. Most of these projects have been intranet based web sites connected to a SQL database. In the last 6 years, Mike has focused on C# and SQL Server development.
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
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.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RepeaterUserControl.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved