C# – Custom Repeater Control with Paging and Page Navigation Controls

asp.netc

I'm trying to create a customer repeater with Paging and accompanying controls e.g. Next Prev buttons.

So far I have the custom repeater with Paged data working fine, and I can get it to render the navigation buttons aswell but I can't assign events to the Navigation LinkButtons.

Here's the Custom Repeater class:

using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data;
using System.Collections;
using System;

namespace ASPresentation.Controls 
{
[ToolboxData("<cc:PagedRepeater runat=server></cc:PagedRepeater>")]
public class PagedRepeater : Repeater
{
    public int PageSize { get; set; }
    public int CurrentPageIndex { get; set; }
    public PagedDataSource pagedData = new PagedDataSource();
    LinkButton NextBtn = new LinkButton();
    LinkButton PrevBtn = new LinkButton();

    public bool IsLastPage
    {
        get
        {
            return pagedData.IsLastPage;
        }
    }
    public bool IsFirstPage
    {
        get
        {
            return pagedData.IsFirstPage;
        }
    }

    public override object DataSource
    {
        get
        {
            return base.DataSource;
        }
        set
        {
            pagedData.DataSource = (IEnumerable)value;
        }
    }

    protected void NextButtonClick(object sender, EventArgs e)
    {
        if (!IsLastPage)
        {
            CurrentPageIndex++;
        }
    }

    protected void PrevButtonClick(object sender, EventArgs e)
    {
        if (!IsFirstPage)
        {
            CurrentPageIndex--;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        NextBtn.Text = "Next";
        PrevBtn.Text = "Prev";
        NextBtn.Click += new EventHandler(NextButtonClick);
        PrevBtn.Click += new EventHandler(PrevButtonClick);
        base.OnInit(e);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        base.Controls.Add(PrevBtn);
        base.Controls.Add(NextBtn);
        base.Render(writer);
    }

    public override void DataBind()
    {
        pagedData.AllowPaging = true;
        pagedData.PageSize = PageSize;
        pagedData.CurrentPageIndex = CurrentPageIndex;
        base.DataSource = pagedData;
        base.DataBind();
    }
}
}

Anyone got any ideas?

Best Answer

Try making this control a CompositeControl instead of inheriting from Repeater. Inside the composite, instantiate your Repeater, PagedDataSource, button controls, and any other controls necessary and add them to the control tree via overriding CreateChildControls. You can set up your event handlers at this point, too. Then, expose the repeater's templates in the composite. I am offering this suggestion as a different approach as you are essentially writing a composite control. However, you're not adding the buttons to one of the templates of the repeater at render time (say the footer), so you may be losing something.

Related Topic