Resources » Code Snippets » ASP.NET WebForms

How to create custom paging in Data List control?


Posted Date: 10-Jul-2011  Last Updated:   Category: ASP.NET WebForms    
Author: Member Level: Diamond    Points: 20


In this article I have explained about how to create custom paging in Datalist control like Google Paging/Grid view page. We want fetch more number of records from database and bind into data list, that time difficult to see all data in the same page, so we need to split that data into different page and display it. This concept is applied in this code snippet. Learn how to create custom paging in Data List control?



Find the code to create custom paging in Data List control


Description
The Data List control in ASP.NET used to bind data and display data to user with help of custom design. For example we have used Grid view not able to use Tables inside of that control. But here in the data list control we have use table and its properties inside of data list view control.

In the below example code I have used table control inside of data list for design my ouput data in custom format.

Client side

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>DataList Example</title>
<style type="text/css">
.htext
{
background-color: #033280;
color: White;
font-size: 12px;
font-weight: bold;
}
.celltext
{
background-color: #E9F3F8;
color: #000000;
font-size: 12px;
font-weight: bold;
}
a
{
text-decoration: none;
font-weight:bold;
}
a:hover
{
text-decoration: underline;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="700" align="center" cellspacing="0" cellpadding="0">
<tr>
<td height="40" colspan="2"><b>DataList Custom Paging Example</b></td>
</tr>
<tr>
<td width="50%" height="50">
Select number of items to be displayed per page
</td>
<td width="50%">
<asp:DropDownList ID="ddlIndex" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlIndex_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="center" width="100%" colspan="2" valign="top" style="padding-top: 10px; padding-bottom: 10px;">
<asp:DataList runat="server" ID="DListEmp" cellpadding="0" cellspacing="0">
<HeaderTemplate>
<table width="500" bgcolor="#ffffff" cellpadding="0" cellspacing="0">
<tr>
<td width="150" align="center" height="30" class="htext"><b>Employee No.</b></td>
<td width="150" align="center" height="30" class="htext"><b>Employee Name</b></td>
<td width="150" align="center" height="30" class="htext"><b>Employee Department</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td width="150" align="center" height="30" class="celltext"><%#Eval("eno") %></td>
<td width="150" align="center" height="30" class="celltext"><%#Eval("empname") %></td>
<td width="150" align="center" height="30" class="celltext"><%#Eval("dept") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
</td>
</tr>
<tr>
<td align="center" height="40" valign="middle" colspan="2">
<table>
<tr>
<td colspan="5"> </td>
</tr>
<tr>
<td width="80" valign="top" align="center"><asp:LinkButton ID="lnkFirst"
runat="server" onclick="lnkFirst_Click">First</asp:LinkButton></td>
<td width="80" valign="top" align="center"><asp:LinkButton ID="lnkPrevious"
runat="server" onclick="lnkPrevious_Click">Previous</asp:LinkButton></td>
<td>
<asp:DataList ID="DataListPaging" runat="server" RepeatDirection="Horizontal"
onitemcommand="DataListPaging_ItemCommand"
onitemdatabound="DataListPaging_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="Pagingbtn" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="newpage" Text='<%# Eval("PageText") %> '></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</td>
<td width="80" valign="top" align="center">
<asp:LinkButton ID="lnkNext" runat="server" onclick="lnkNext_Click">Next</asp:LinkButton>
</td>
<td width="80" valign="top" align="center">
<asp:LinkButton ID="lnkLast" runat="server" onclick="lnkLast_Click">Last</asp:LinkButton>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" height="40" colspan="2"><asp:Label ID="lblpage" runat="server" Text=""></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>
</html>

They are various template properties are used in the Data List control. These three templates are mostly used template in the Data List.

HeaderTemplate: HeaderTemplate is used to write header part of the Data List. In this code snippet I have used this template for write Header text for each column records.

ItemTemplate: ItemTemplate is used to bind repeated Item content in the Data List Control. In this example I have used this template for bind datatable values in to the data list item.

FooterTemplate: Footer template is used to write text on the footer of Data List control. I used this template for closing Table tag.

In the above code I have used another one "DataListPaging" data list. It is used to display page options like 1 2 3 …etc. based on the pages available in the data list.

Server side
In the server side code I have get selected items number per page by user from drop down list and bind that specified number of items in the Data List control.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
PagedDataSource pgsource = new PagedDataSource();
int findex, lindex;
DataRow dr;

protected void Page_Load(object sender, EventArgs e)
{
//During first time page load this method call
if (!Page.IsPostBack)
{
BindDataList();
LoadDDL();
}
}

DataTable GetData()
{
DataTable dtable = new DataTable();
//Create column names for Datatable "dtable"
dtable.Columns.Add("eno");
dtable.Columns.Add("empname");
dtable.Columns.Add("dept");
for (int i = 1; i <= 100; i++)
{
//Create rows for DataTable "dtable" and assign values for each column
dr = dtable.NewRow();
dr["eno"] = i;
dr["empname"] = "Empname " + i;
dr["dept"] = "Dept. Name ";
dtable.Rows.Add(dr);
}
//Return DataTable "dtable" with its data
return dtable;
}

private void BindDataList()
{
//Create new DataTable dt
DataTable dt = GetData();
pgsource.DataSource = dt.DefaultView;

//Set PageDataSource paging
pgsource.AllowPaging = true;

//Set number of items to be displayed in the DataList using drop down list
if (ddlIndex.SelectedIndex == -1 || ddlIndex.SelectedIndex == 0)
{
pgsource.PageSize = 10;
}
else
{
pgsource.PageSize = Convert.ToInt32(ddlIndex.SelectedItem.Value);
}


//Get Current Page Index
pgsource.CurrentPageIndex = CurrentPage;

//Store it Total pages value in View state
ViewState["totpage"] = pgsource.PageCount;

//Below line is used to show page number based on selection like "Page 1 of 20"
lblpage.Text = "Page " + (CurrentPage + 1) + " of " + pgsource.PageCount;

//Enabled true Link button previous when current page is not equal first page
//Enabled false Link button previous when current page is first page
lnkPrevious.Enabled = !pgsource.IsFirstPage;

//Enabled true Link button Next when current page is not equal last page
//Enabled false Link button Next when current page is last page
lnkNext.Enabled = !pgsource.IsLastPage;

//Enabled true Link button First when current page is not equal first page
//Enabled false Link button First when current page is first page
lnkFirst.Enabled = !pgsource.IsFirstPage;

//Enabled true Link button Last when current page is not equal last page
//Enabled false Link button Last when current page is last page
lnkLast.Enabled = !pgsource.IsLastPage;

//Bind resulted PageSource into the DataList
DListEmp.DataSource = pgsource;
DListEmp.DataBind();

//Create Paging in the second DataList "DataListPaging"
doPaging();
}

private void doPaging()
{
DataTable dt = new DataTable();
//Add two column into the DataTable "dt"
//First Column store page index default it start from "0"
//Second Column store page index default it start from "1"
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");

//Assign First Index starts from which number in paging data list
findex = CurrentPage - 5;

//Set Last index value if current page less than 5 then last index added "5" values to the Current page else it set "10" for last page number
if (CurrentPage > 5)
{
lindex = CurrentPage + 5;
}
else
{
lindex = 10;
}

//Check last page is greater than total page then reduced it to total no. of page is last index
if (lindex > Convert.ToInt32(ViewState["totpage"]))
{
lindex = Convert.ToInt32(ViewState["totpage"]);
findex = lindex - 10;
}

if (findex < 0)
{
findex = 0;
}

//Now creating page number based on above first and last page index
for (int i = findex; i < lindex; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}

//Finally bind it page numbers in to the Paging DataList
DataListPaging.DataSource = dt;
DataListPaging.DataBind();
}

private int CurrentPage
{
get
{ //Check view state is null if null then return current index value as "0" else return specific page viewstate value
if (ViewState["CurrentPage"] == null)
{
return 0;
}
else
{
return ((int)ViewState["CurrentPage"]);
}
}
set
{
//Set View statevalue when page is changed through Paging DataList
ViewState["CurrentPage"] = value;
}
}

protected void DataListPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("newpage"))
{
//Assign CurrentPage number when user click on the page number in the Paging DataList
CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
//Refresh DataList "DlistEmp" Data once user change page
BindDataList();
}
}

protected void lnkFirst_Click(object sender, EventArgs e)
{
//If user click First Link button assign current index as Zero "0" then refresh DataList "DlistEmp" Data.
CurrentPage = 0;
BindDataList();
}

protected void lnkLast_Click(object sender, EventArgs e)
{
//If user click Last Link button assign current index as totalpage then refresh DataList "DlistEmp" Data.
CurrentPage = (Convert.ToInt32(ViewState["totpage"]) - 1);
BindDataList();
}

protected void lnkPrevious_Click(object sender, EventArgs e)
{
//If user click Previous Link button assign current index as -1 it reduce existing page index.
CurrentPage -= 1;
//refresh DataList "DlistEmp" Data
BindDataList();
}

protected void lnkNext_Click(object sender, EventArgs e)
{
//If user click Next Link button assign current index as +1 it add one value to existing page index.
CurrentPage += 1;

//refresh DataList "DlistEmp" Data
BindDataList();
}

void LoadDDL()
{
//Below code is used to bind values in the drop down list
for (int i = 1; i <= 10; i++)
{
ddlIndex.Items.Add(i.ToString());
}
ddlIndex.Items.Insert(0, new ListItem("--Select--", "--Select--"));
}

protected void ddlIndex_SelectedIndexChanged(object sender, EventArgs e)
{
//Set Default current index Zero default and refresh it page size based on Drop Down List selected
CurrentPage = 0;
BindDataList();
}
protected void DataListPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
//Enabled False for current selected Page index
LinkButton lnkPage = (LinkButton)e.Item.FindControl("Pagingbtn");
if (lnkPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkPage.Enabled = false;
}
}
}

Output:
Output of the above code it seem like this

Output1


Below output I show based on drop down list value change
Ouput2


Source code:
Download the attached source code and try to change list of items to be display in the Data List with help of drop down list.
Front End: ASP.NET
Code Behind: C#

Conclusion:
I hope this article is help to know about Data List control and its uses in ASP.NET.


Did you like this resource? Share it with your friends and show your love!

Responses to "How to create custom paging in Data List control?"
Guest Author: Nilesh     16 Dec 2011
This is really good work done
very helpful
appreciate your time

Thanks



Author: Ravindran    16 Dec 2011Member Level: Diamond   Points : 0
Thanks Nilesh


Guest Author: Kevin24     09 Jan 2012
Hi,

I'm pretty new to C# coding etc and I have been looking at your sample paging. It's one of the best, for me because I can follow quite a bit of the logic (but not all of the coding concepts).

However, I was thinking if you wanted to use with a database, what changes would you have to make. An example would be great as I could then compare. Many thanks.



Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India