DataPager control is used for paging in Gridview, Listview,Repeater controls in Asp.Net. In this article we discuss about how to do paging for Asp.Net Listview control.
Open Microsoft Visual Studio => Create New Asp.Net Web Application
Now Add Listview and DataPager controls in Default.aspx page as shown below.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DataPagerExp._Default" %>
<!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>Paging using Data Pager Control in Asp.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="listview1" runat="server">
<LayoutTemplate>
<table border="1">
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Id")%></td>
<td><%# Eval("Name")%></td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<tr>
<td>
No Data Found
</td>
</tr>
</EmptyDataTemplate>
</asp:ListView>
<asp:DataPager ID="lvDataPager" runat="server" OnPreRender="lvDataPager_PreRender" PagedControlID="listview1" PageSize="10" QueryStringField="pageid">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="False" ShowNextPageButton="False"
ShowPreviousPageButton="False" />
<asp:NumericPagerField NumericButtonCssClass="datapagerStyle" ButtonCount="10"/>
<asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="False" ShowNextPageButton="False"
ShowPreviousPageButton="False" />
</Fields>
</asp:DataPager>
</div>
</form>
</body>
</html>
As shown above we are providing the Listview control Id to the DataPager control PagedControlID property. Provide number of records you want to show per page for PageSize property and Query string filed name for QueryStringField.
Now bind the data to Listview by creating DataTable as shown below.
Default.aspx.cs
using System;
using System.Data;
namespace DataPagerExp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
try
{
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
for (int i = 1; i < 101; i++)
{
dt.Rows.Add(i.ToString(), "Name_" + i.ToString());
}
listview1.DataSource = dt;
listview1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
protected void lvDataPager_PreRender(object sender, EventArgs e)
{
BindData();
}
}
}
As shown above we have to bind data again in DataPager control PreRender Event. This event is fired whenever page is changed.
Now execute the application and the output is a shown below.
As shown above if we click on any page it displays that particular data.