If you ever tried to use GridView you probably know that it is very easy to page the data. But if you ever wanted to display this paged data in a Repeater you might have thought it's not that easy. Luckily, there is the PagedDataSource class that makes it quite easy.
Let's say we want to display a list of users in a repeater. The User object has Name, Age, Address, Phone and Email properties. So, we need a repeater control on our form and two buttons for "previous page" and "next page" actions.
First, we'll create BindList method:
public void BindList()
{
PagedDataSource pagedUserList = new PagedDataSource();
List userList = myRepository.GetUserList(); // myRepository is a class that retreives tha data
// Set pagedUserList
pagedUserList.AllowPaging = true;
pagedUserList.DataSource = userList;
pagedUserList.PageSize = 10;
pagedUserList.CurrentPageIndex = Convert.ToInt32(Viewstate["CurrentPage"].ToString());
// Data bind
myRepeater.DataSource = pagedUserList;
myRepeater.DataBind();
}
Next, create two event handlers that will handle clicks for btnPrev and btnNext buttons. Basically, we'll just change the current page index stored in the ViewState and call the BindList method.
private void btnPrev_Click(object sender, System.EventArgs e)
{ ViewState["CurrentPage"] = Convert.ToInt32(ViewState["CurrentPage"]) - 1;
BindList();
}
private void btnNext_Click(object sender, System.EventArgs e)
{
ViewState["CurrentPage"] = Convert.ToInt32(ViewState["CurrentPage"]) + 1;
BindList();
}
Next, in Page_Load event we'll define the start page index and call the BindList method:
if (!isPostBack)
{
ViewState["CurrentPage"] = 1;
BindList();
}
That's all. You can easily extend this code by hiding btnPrev if rendering first page and hiding btnNext if rendering last page. If you want to practice more, change the code to display page numbers as clickable links instead of Prev - Next buttons.