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

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.

     /// <summary>
        /// Creates the child controls.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            EnabledEmptyTemplate();
        }

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

        }

        /// <summary>
        /// Enableds the empty template.
        /// </summary>
        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.

      /// <summary>
        /// Enableds the empty template.
        /// </summary>
        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

      /// <summary>
        /// Enableds the empty template.
        /// </summary>
        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.

      /// <summary>
        /// Enableds the empty template.
        /// </summary>
        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

       /// <summary>
        /// Raises the DataBinding event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        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;

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

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

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

        /// <summary>
        /// Gets or sets the empty template.
        /// </summary>
        /// <value>The empty template.</value>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate EmptyTemplate
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the empty template.
        /// </summary>
        /// <value>The empty template.</value>
        [PersistenceMode(PersistenceMode.Attribute)]
        public bool ShowCount
        {
            get;
            set;
        }

        #endregion

        #region Repeater Methods

        /// <summary>
        /// Creates the child controls.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            EnabledEmptyTemplate();
        }

        /// <summary>
        /// Raises the DataBinding event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        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 ));
            }
        }

        /// <summary>
        /// Enableds the empty template.
        /// </summary>
        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

4 thoughts on “ASP.NET Custom Repeater Control with EmptyTemplate, ShowHeaderWhenEmpty,ShowFooterWhenEmpty,ShowCount Properties

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s