Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

ASP.NET Custom Repeater Control with EmptyTemplate, ShowHeaderWhenEmpty,ShowFooterWhenEmpty,ShowCount Properties

, 4 Apr 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
If you have worked with ASP.NET GridView Control you must be aware of GridView.EmptyDataTemplate Property  which Gets or sets the user-defined content for the empty data row when a GridView control  data source has no records. Similarly ShowHeaderWhenEmpty property allows you to show or hide the Hea

If you have worked with ASP.NET GridView Control you must be aware of GridView.EmptyDataTemplate Property  which Gets or sets the user-defined content for the empty data row when a GriimagedView control  data source has no records. Similarly ShowHeaderWhenEmpty property allows you to show or hide the Header row when there is no records. These are the really good and very frequent required properties. Now, if you are working with the Repeater Control, it doesn’t have any direct features which enables you to set user define content when data source is empty. In this blog post I will discuss how we can create a custom ASP.NET Repeater control with support of EmptyTemplate along with few more important features.

The basis of the complete implementation is stands on developing a custom ASP.NET Control. Here I will be developing a custom ASP.NET Repeater control which inherits  from Repeater as you can see in the bellow code snippet.

image

Now, once you inherits you control from default Repeater control, you have access of all methods and properties of Repeater control. The most important thing to here that you need to know about ITemplate Interface. ITemplate defines the behavior for populating a templated ASP.NET server control with child controls . These ITemplate having a method InstantiateIn which actually instantiate the template with in the control object.  As we required an Template here I created a  properties named “EmptyTemplate” of type “ITemplate”

   [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate EmptyTemplate
        {
            get;
            set;
        }

In the above code snippets you have notices I have added one attributes as

 PersistenceMode(PersistenceMode.InnerProperty)] 

These actually define the type of the property with PersistenceMode Enumeration. InnerProperty tells the control that these properties should be used a inner nested tag not as top level attributes.  I discussed about few other values in later part of this article.

Once we are done with the Property define , we just need to override the CreateChildControls() and OnDataBinding() Events.

     /// <span class="code-SummaryComment"><summary>
</span>        /// Creates the child controls.
        /// <span class="code-SummaryComment"></summary>
</span>        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            EnabledEmptyTemplate();
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Raises the DataBinding event.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
</span>        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            EnabledEmptyTemplate();

        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Enableds the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        private void EnabledEmptyTemplate()
        {
            if (this.Items.Count <= 0 && EmptyTemplate != null)
            {
                this.Controls.Clear();

                EmptyTemplate.InstantiateIn(this);

            }
        }

While overriding those methods, I have internally called a method EnabledEmptyTemplate() which actually checks for the Item Counts, if its &lt;=0,  it will Instantiate the EmptyTemplate.

That’s all. If you build the control, you will get an Control Icon with in ToolBox, which you can directly drag and drop.

image

Now let’s consider you have bellow Student Data Source which you want to bind with this gridview

Sample Student Data Source and binding with repeater

  public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<MyClass> names = new List<MyClass>()
            {
            new MyClass { Name ="Student 1", Address="Address 1"},
            new MyClass { Name ="Student 2", Address="Address 2"},
            new MyClass { Name ="Student 3", Address="Address 3"},
            new MyClass { Name ="Student 4", Address="Address 4"}
            };
                  ExRepeater1.DataSource = names;
            ExRepeater1.DataBind();
        }
    }

    class MyClass
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }

Design View for Custom Repeater

    <cc1:ExRepeater ID="ExRepeater1" runat="server"  >
            <HeaderTemplate>
                <table>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Address
                        </td>
                    </tr>
                 </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <%#Eval("Name")%>
                    </td>

                    <td>
                        <%#Eval("Address")%>
                    </td>
                </tr>
            </ItemTemplate>
            <EmptyTemplate>
               <tr><td> No Records Exist !!!!</td></tr>
            </EmptyTemplate>
            <FooterTemplate>
            </table>
            </FooterTemplate>
        </cc1:ExRepeater>

Output

image

Now, if there is no records in the data source, output will be look like below

image

Well, this is exactly what we were looking for. So now you have one Template called “EmptyTemplate” where you can put what ever the content you want to rendered if the data source is empty.

ShowHeaderWhenEmpty

You have noticed, the message “No Records Exists” is being displayed along with the header. Now if you want the same features like GridView, that you need control on the showing or hiding header when records is empty.

Let’s add a bool type property with name ShowHeaderWhenEmpty ,

image

This properties will accepts a Boolean value based on that Header will be shown. One more point over here is,  PersistenceMode.Attribute, which means I am going to use the properties as a top level attributes tag. So ShowHeaderWhenEmpty will be accessible as shown in below

image

Below Snippets describes how to implement the ShowHeaderWhenEmpty Properties.

      /// <span class="code-SummaryComment"><summary>
</span>        /// Enableds the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        private void EnabledEmptyTemplate()
        {
            if (this.Items.Count <= 0 && EmptyTemplate != null)
            {
                this.Controls.Clear();

                // Instantiate Header Template When Item count 0
                if (ShowHeaderWhenEmpty == true)
                {
                    HeaderTemplate.InstantiateIn(this);
                }

                EmptyTemplate.InstantiateIn(this);
            }
        }

ShowFooterWhenEmpty

Like Header, you can implement the same to show or hide footer when there is no records in repeater.

image

      /// <span class="code-SummaryComment"><summary>
</span>        /// Enableds the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        private void EnabledEmptyTemplate()
        {
            if (this.Items.Count <= 0 && EmptyTemplate != null)
            {
                this.Controls.Clear();
                EmptyTemplate.InstantiateIn(this);
            // Instantiate Footer Template When Item count 0
                if (ShowFooterWhenEmpty == true)
                {
                    FooterTemplate.InstantiateIn(this);
                }

            }
        }

ShowCount

By this properties I just wanted to show the customization or enhancement idea. Let’s say you want to display the number of total records at the end of the repeater, so by using these properties you can enable or disabled it.

image

If you make it true, you will get the number of records count at the end of repeater records.

image

Below is the implementation for the same.

      /// <span class="code-SummaryComment"><summary>
</span>        /// Enableds the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        private void EnabledEmptyTemplate()
        {
            if (this.Items.Count <= 0 && EmptyTemplate != null)
            {
                this.Controls.Clear();

                // Instantiate Header Template When Item count 0
                if (ShowHeaderWhenEmpty == true)
                {
                    HeaderTemplate.InstantiateIn(this);
                }

                EmptyTemplate.InstantiateIn(this);
            }
        }

ShowFooterWhenEmpty

Like Header, you can implement the same to show or hide footer when there is no records in repeater.

image

       /// <span class="code-SummaryComment"><summary>
</span>        /// Raises the DataBinding event.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
</span>        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            EnabledEmptyTemplate();
            if (ShowCount == true)
            {

                this.Controls.Add(new LiteralControl("<br/>Total Number of Records : " + this.Items.Count ));
            }
        }

Put everything Together :

// Custom Repeater With EmptyItemTemplate and ShowHeaderWhenEmpty Properties
namespace RepeaterTest
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.ComponentModel;
    using System.Web.UI;

    /// <span class="code-SummaryComment"><summary>
</span>    /// Advance ASP.NET Repeater with EmptyTemplate, ShowHeaderWhenEmpty, ShowFooterWhenEmpty
    /// <span class="code-SummaryComment"></summary>
</span>    [ToolboxData("<{0}:ExRepeater runat="server">")]
    public class ExRepeater : Repeater
    {
        #region Repeater Properties

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets or sets a value indicating whether [show header when empty].
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><value>
</span>        /// 	<span class="code-SummaryComment"><c>true</c> if [show header when empty]; otherwise, <c>false</c>.
</span>        /// <span class="code-SummaryComment"></value>
</span>        [PersistenceMode(PersistenceMode.Attribute)]
        public bool ShowHeaderWhenEmpty
        {
            get;
            set;
        }

        [PersistenceMode(PersistenceMode.Attribute)]
        public bool ShowFooterWhenEmpty
        {
            get;
            set;
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets or sets the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><value>The empty template.</value>
</span>        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate EmptyTemplate
        {
            get;
            set;
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets or sets the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><value>The empty template.</value>
</span>        [PersistenceMode(PersistenceMode.Attribute)]
        public bool ShowCount
        {
            get;
            set;
        }

        #endregion

        #region Repeater Methods

        /// <span class="code-SummaryComment"><summary>
</span>        /// Creates the child controls.
        /// <span class="code-SummaryComment"></summary>
</span>        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            EnabledEmptyTemplate();
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Raises the DataBinding event.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
</span>        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            EnabledEmptyTemplate();
            if (ShowCount == true)
            {

                this.Controls.Add(new LiteralControl("<br/>Total Number of Records : " + 
                    this.Items.Count ));
            }
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Enableds the empty template.
        /// <span class="code-SummaryComment"></summary>
</span>        private void EnabledEmptyTemplate()
        {
            if (this.Items.Count <= 0 && EmptyTemplate != null)
            {
                this.Controls.Clear();

                // Instantiate Header Template When Item count 0
                if (ShowHeaderWhenEmpty == true)
                {
                    HeaderTemplate.InstantiateIn(this);
                }

                EmptyTemplate.InstantiateIn(this);
            }
        }

        #endregion
    }
}

Summary : In this post I have explained how you can customize your repeater control by adding must needed features likes EmptyTemplate, ShowHeaderWhenEmpty, ShowFooterWhenEmpty, ShowCount.

Hope this will help !

Cheers !

AJ

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhijit Jana
Technical Lead
India India
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide
Follow on   Twitter

Comments and Discussions

 
Suggestionsuggestions for minor improvements Pinmemberjohnmcalvert14-Jul-13 12:27 
GeneralMy vote of 5 Pinmemberjohnmcalvert14-Jul-13 11:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 4 Apr 2011
Article Copyright 2011 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid