//// Read sample item info from XML document into a DataSet
//DataSet Items = new DataSet();
//Items.ReadXml(MapPath("Items.xml"));
// Populate the repeater control with the Items DataSet
PagedDataSource objPds =
new PagedDataSource();
//objPds.DataSource = Items.Tables[0].DefaultView;
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
objPds.DataSource = dv;
objPds.AllowPaging =
true;
objPds.PageSize = 3;
objPds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text =
"Page: " + (CurrentPage + 1).ToString() +
" of "
+ objPds.PageCount.ToString();
// Disable Prev or Next buttons if necessary
cmdPrev.Enabled = !objPds.IsFirstPage;
cmdNext.Enabled = !objPds.IsLastPage;
DataList1.DataSource = objPds;
DataList1.DataBind();
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o =
this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default to showing the first page
else
return (int)o;
This is code how we can paging datalist in asp.net 2003 [Yes]
Imports System.Data
Imports System.Data.OleDb
Public Class Paging
Inherits System.Web.UI.Page
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Dim pagedData As New PagedDataSource
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
doPaging()
End Sub
Dim cs As New DataBase
Public Function getTheData() As DataTable
Dim DS As New DataSet
Dim strConnect As New OleDbConnection(cs.Cs1)
Dim objSQLAdapter As New OleDbDataAdapter("SELECT * FROM MyPhotos_items", strConnect)
objSQLAdapter.Fill(DS, "Portfolio_items")
Return DS.Tables("Portfolio_items").Copy
End Function
Public Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 5
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
theDataList.DataSource = pagedData
theDataList.DataBind()
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNext.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex + 1))
End Sub
Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnPrev.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex - 1))
End Sub
Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLast.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.PageCount - 1))
End Sub
This code works great, but is there anyway to set the current page to page 1 when you run this code?
Im using this datalist to display a list of products. If I move to the second page, and filter the list of products still stays on the second page. Even though the list of products after filtered is less than one page.
I use another method, written 100% by a genius (me! lol)
I love it, because it's simple and requires very little code...
In your page load:
- initialize session page counter..
- call the function that will create the links..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("pageNum") = 1
End If
MakePageLinks()
End Sub
Here's mine: it counts total records from the datasource; I want 15 items per page here.
Protected Sub MakePageLinks()
Dim ds As New DataSet
Dim db As New DataBase
ds = db.query("SELECT Count(*) as numObs FROM Observations WHERE reviewed=1")
Dim numObs As Integer = ds.Tables(0).Rows(0).Item("numObs")
Dim numPages As Integer = numObs / 15
For i As Integer = 1 To numPages
Dim pageLink As New LinkButton
pageLink.Text = "[" + i.ToString + "]"
pageLink.CssClass = "normal"
pageLink.CommandArgument = i
pageLink.PostBackUrl = "#"
AddHandler pageLink.Click, AddressOf Me.PageLink_Click
pageLinks.controls.add(pageLink)
RadAjaxManager1.AjaxSettings.AddAjaxSetting(pageLink, TopObsList, LoadingPanel1)
Next
End Sub
(pageLinks is a tablecell, see below)
I also use the Telerik controls, so replace RadAjaxManager1.AjaxSettings.AddAjaxSetting(pageLink, TopObsList, LoadingPanel1)
with code to register a control as an async trigger to update panel containing the datalist...
Protected Sub PageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Session("pageNum") = sender.commandargument
End Sub
Here you see I added next and prev links to, here's the code for them:
Protected Sub nextPageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles nextPageLink.Click
Session("pageNum") += 1
End Sub
Protected Sub prevPageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles prevPageLink.Click
If Session("pageNum") > 1 Then
Session("pageNum") -= 1
End If
End Sub
(they must also be ajaxified)
And finally, your datasource for the datalist should look something like this:
<asp:SqlDataSource runat="server" ID="acceptedDS"
ProviderName="System.Data.SqlClient"
OldValuesParameterFormatString="original_{0}"
ConnectionString="<%$ ConnectionStrings:yourConnectionString %>"
SelectCommand="declare @maxNum integer;SET @maxNum=(SELECT MAX(obs_num) FROM Observations); SELECT DISTINCT TOP 15 * FROM Observations WHERE reviewed=1 AND obs_num<=@maxNum-(15*(@pageNum-1)) ORDER BY obs_num DESC">
<SelectParameters>
<asp:SessionParameter Name="pageNum" Type="int32" SessionField="pageNum" />
</SelectParameters>
</asp:SqlDataSource>
This can easily be adpated to use querystring parameters instead of session.
Simple, efficient solution... If you know your way around ajax and sql...
Validation Complete
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
I'll always mark your post(s) as answer when it is!
norbertacker...
Member
20 Points
7 Posts
DataList Paging
May 08, 2007 06:38 PM|LINK
Is there a way to set up paging for a datalist?
Thank you,
NorbertmeLearnASP.net
limno
All-Star
117340 Points
8005 Posts
Moderator
MVP
Re: DataList Paging
May 08, 2007 06:53 PM|LINK
Yes.
One way you can do this is to use a PagedDataSource. You can find more information from 4guysfromrolla.com site.
Here is a sample:
<table width="100%" border="0"> <tr> <td> DataList control with Paging functionality</td> </tr> <tr> <td> <asp:label id="lblCurrentPage" runat="server"></asp:label></td> </tr> <tr> <td> <asp:button id="cmdPrev" runat="server" text=" << " onclick="cmdPrev_Click"></asp:button> <asp:button id="cmdNext" runat="server" text=" >> " onclick="cmdNext_Click"></asp:button></td> </tr> </table>
<asp:DataList ID="DataList1" runat="server" DataKeyField="title_id" > <ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("title_id", "anotherpage.aspx?title_id={0}") %>' Text='<%# Bind("title_id") %>' ></asp:HyperLink>title_id:
<asp:Label ID="title_idLabel" runat="server" Text='<%# Eval("title_id") %>'></asp:Label><br />title:
<asp:Label ID="titleLabel" runat="server" Text='<%# Eval("title") %>'></asp:Label><br />type:
<asp:Label ID="typeLabel" runat="server" Text='<%# Eval("type") %>'></asp:Label><br />price:
<asp:Label ID="priceLabel" runat="server" Text='<%# Eval("price","{0:c}") %>'></asp:Label><br /> <asp:linkbutton ID="Linkbutton3" runat="server" commandname="Edit" text=' <%# "Edit" + Eval("title_id") %>' />
</ItemTemplate> </asp:DataList> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Pubs %>" SelectCommand="SELECT [title_id], [title], [type], [price] FROM [titles]"> </asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
ItemsGet();
}
}
private void ItemsGet(){
//// Read sample item info from XML document into a DataSet //DataSet Items = new DataSet(); //Items.ReadXml(MapPath("Items.xml")); // Populate the repeater control with the Items DataSet PagedDataSource objPds = new PagedDataSource(); //objPds.DataSource = Items.Tables[0].DefaultView; DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);objPds.DataSource = dv;
objPds.AllowPaging =
true;objPds.PageSize = 3;
objPds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text =
"Page: " + (CurrentPage + 1).ToString() + " of "+ objPds.PageCount.ToString();
// Disable Prev or Next buttons if necessarycmdPrev.Enabled = !objPds.IsFirstPage;
cmdNext.Enabled = !objPds.IsLastPage;
DataList1.DataSource = objPds;
DataList1.DataBind();
}
public int CurrentPage{
get{
// look for current page in ViewState object o = this.ViewState["_CurrentPage"]; if (o == null) return 0; // default to showing the first page else return (int)o;}
set{
this.ViewState["_CurrentPage"] = value;}
}
protected void cmdPrev_Click(object sender, System.EventArgs e){
// Set viewstate variable to the previous pageCurrentPage -= 1;
// Reload controlItemsGet();
}
protected void cmdNext_Click(object sender, System.EventArgs e){
// Set viewstate variable to the next pageCurrentPage += 1;
// Reload controlItemsGet();
}
Format your SQL query with instant sql formatter:
http://www.dpriver.com/pp/sqlformat.htm
KBrocksi_SEC
Contributor
3382 Points
627 Posts
Re: DataList Paging
May 08, 2007 07:06 PM|LINK
Hi,
I would recommend reading the following links:
http://aspalliance.com/articleViewer.aspx?aId=157&pId= (ASP.Net 1.1)
http://weblogs.asp.net/scottgu/archive/2006/01/07/434787.aspx (ASP.Net 2.0)
HTH,
Haissam
All-Star
37421 Points
5632 Posts
Re: DataList Paging
May 08, 2007 07:09 PM|LINK
Check below article
Extending Datalist Funtionality
HC
MCAD.NET
| Blog |
norbertacker...
Member
20 Points
7 Posts
Re: DataList Paging
May 09, 2007 02:54 AM|LINK
Thank you everyone for assisting me. I was able to get it working.
Since most of the articles are in C# here is my solution in VB:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim conn As SqlConnection
Dim ds As New DataSet
Dim adapter As SqlDataAdapter
' Read the connection string from Web.config
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings( _
"myDB").ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
'use a stored proc
adapter = New SqlDataAdapter("usp_displayAll", conn)
adapter.Fill(ds)
Dim objPds As PagedDataSource = New PagedDataSource
objPds.DataSource = ds.Tables(0).DefaultView
objPds.AllowPaging = True
objPds.PageSize = 5
Dim CurPage As Integer
If Not (Request.QueryString("Page") Is Nothing) ThenCurPage = Convert.ToInt32(Request.QueryString("Page"))
Else
CurPage = 1
End If
objPds.CurrentPageIndex = CurPage - 1
lblCurrentPage.Text =
"Page: " + CurPage.ToString If Not objPds.IsFirstPage ThenlnkPrev.NavigateUrl = Request.CurrentExecutionFilePath +
"?Page=" + Convert.ToString(CurPage - 1) End If If Not objPds.IsLastPage ThenlnkNext.NavigateUrl = Request.CurrentExecutionFilePath +
"?Page=" + Convert.ToString(CurPage + 1) End IfdlDisplayAll.DataSource = objPds
dlDisplayAll.DataBind()
End Sub------------------------------------------------
Norbert
meLearnASP.net
datalist paging
Ahmad Abu Sh...
Member
14 Points
9 Posts
Re: DataList Paging
Aug 07, 2007 01:00 PM|LINK
This is code how we can paging datalist in asp.net 2003 [Yes]
Imports System.Data
Imports System.Data.OleDb
Public Class Paging
Inherits System.Web.UI.Page
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Dim pagedData As New PagedDataSource
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
doPaging()
End Sub
Dim cs As New DataBase
Public Function getTheData() As DataTable
Dim DS As New DataSet
Dim strConnect As New OleDbConnection(cs.Cs1)
Dim objSQLAdapter As New OleDbDataAdapter("SELECT * FROM MyPhotos_items", strConnect)
objSQLAdapter.Fill(DS, "Portfolio_items")
Return DS.Tables("Portfolio_items").Copy
End Function
Public Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 5
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
' btnPrev.Visible = (Not pagedData.IsFirstPage)
' btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
theDataList.DataSource = pagedData
theDataList.DataBind()
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnNext.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex + 1))
End Sub
Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnPrev.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex - 1))
End Sub
Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLast.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.PageCount - 1))
End Sub
Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnFirst.Click
Response.Redirect(Request.CurrentExecutionFilePath & "?Page=" & (pagedData.CurrentPageIndex = 0))
End Sub
End Class
=================================================
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="PagingDS.aspx.vb" Inherits="DC.Paging"%>
<HTML>
<HEAD>
<title>Paging with ASP.NET - DataSet Example - VB.NET</title>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<body>
<form runat="server" ID="Form1">
<font size="-1" face="Verdana, Arial, Helvetica, sans-serif">
<asp:label id="pageNumber" runat="server" /></font>
<asp:DataList id="theDataList" runat="server" RepeatColumns="3">
<ItemTemplate>
<table id="datalist1" border="0" cellpadding="0">
<tr>
<td>
<font color="#49176d" size="2">
<center><%#DataBinder.Eval(Container.DataItem,"name")%></center>
</font>
<tr>
<td>
<A href='<%#"img.aspx?item_id="& DataBinder.Eval(Container.DataItem,"item_id")%>' target=_blank>
<img height=130 alt="" src='img.aspx?item_id=<%#DataBinder.Eval(Container.DataItem,"item_id")%>' width=130></A>
<hr>
</td>
</tr>
</td> </tr>
</table>
</ItemTemplate>
</asp:DataList>
<asp:ImageButton id="btnFirst" runat="server" ImageUrl="images/a-ll-over.gif"></asp:ImageButton>
<asp:ImageButton id="btnPrev" runat="server" ImageUrl="images/a-l-over.gif"></asp:ImageButton>
<asp:ImageButton ID="btnNext" Runat="server" ImageUrl="images/a-r-over.gif"></asp:ImageButton>
<asp:ImageButton id="btnLast" runat="server" ImageUrl="images/a-rr-over.gif"></asp:ImageButton>
</form>
</body>
</HTML>
Web Developer
Digital Colors Design Co. LLC
P.O. Box 17515 Amman 11195
Mobile: (+962 79) 512 0349
Email:programmer_ahmad@yahoo.com
www.digital-colors.com
terbs
Member
46 Points
51 Posts
Re: DataList Paging
Jun 11, 2008 02:04 AM|LINK
Old thread, but have to thank Norbert for that post!
terbs
Member
46 Points
51 Posts
Re: DataList Paging
Jul 02, 2008 03:45 AM|LINK
This code works great, but is there anyway to set the current page to page 1 when you run this code?
Im using this datalist to display a list of products. If I move to the second page, and filter the list of products still stays on the second page. Even though the list of products after filtered is less than one page.
gem_dark
Member
2 Points
1 Post
Re: DataList Paging
Jul 13, 2008 01:29 PM|LINK
code how we can paging datalist in asp.net 2003 of Ahmad Abu Sharkh show paging in buttom :
- First Page
- Last Page
- Next Page
- Pre Page.
Now, How show paging in number href:
- 1 2 3 4 5 6 7 . . .
Please help me . . .
NNM
Participant
1414 Points
559 Posts
Re: DataList Paging
Feb 05, 2009 09:25 AM|LINK
I use another method, written 100% by a genius (me! lol)
I love it, because it's simple and requires very little code...
In your page load:
- initialize session page counter..
- call the function that will create the links..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("pageNum") = 1
End If
MakePageLinks()
End Sub
Here's mine: it counts total records from the datasource; I want 15 items per page here.
Protected Sub MakePageLinks()
Dim ds As New DataSet
Dim db As New DataBase
ds = db.query("SELECT Count(*) as numObs FROM Observations WHERE reviewed=1")
Dim numObs As Integer = ds.Tables(0).Rows(0).Item("numObs")
Dim numPages As Integer = numObs / 15
For i As Integer = 1 To numPages
Dim pageLink As New LinkButton
pageLink.Text = "[" + i.ToString + "]"
pageLink.CssClass = "normal"
pageLink.CommandArgument = i
pageLink.PostBackUrl = "#"
AddHandler pageLink.Click, AddressOf Me.PageLink_Click
pageLinks.controls.add(pageLink)
RadAjaxManager1.AjaxSettings.AddAjaxSetting(pageLink, TopObsList, LoadingPanel1)
Next
End Sub
(pageLinks is a tablecell, see below)
I also use the Telerik controls, so replace RadAjaxManager1.AjaxSettings.AddAjaxSetting(pageLink, TopObsList, LoadingPanel1)
with code to register a control as an async trigger to update panel containing the datalist...
Protected Sub PageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Session("pageNum") = sender.commandargument
End Sub
Below your datalist, add this:
<br />
<asp:Table runat="server" ID="alignLinks" Width="700" HorizontalAlign="Center">
<asp:TableRow>
<asp:TableCell HorizontalAlign="Left">
<asp:LinkButton runat="server" ID="prevPageLink" CssClass="normal" Text="Previous page" PostBackUrl="#"></asp:LinkButton>
</asp:TableCell>
<asp:TableCell runat="server" ID="pageLinks">
</asp:TableCell>
<asp:TableCell HorizontalAlign="Right">
<asp:LinkButton runat="server" ID="nextPageLink" CssClass="normal" Text="Next page" PostBackUrl="#"></asp:LinkButton>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Here you see I added next and prev links to, here's the code for them:
Protected Sub nextPageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles nextPageLink.Click
Session("pageNum") += 1
End Sub
Protected Sub prevPageLink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles prevPageLink.Click
If Session("pageNum") > 1 Then
Session("pageNum") -= 1
End If
End Sub
(they must also be ajaxified)
And finally, your datasource for the datalist should look something like this:
<asp:SqlDataSource runat="server" ID="acceptedDS"
ProviderName="System.Data.SqlClient"
OldValuesParameterFormatString="original_{0}"
ConnectionString="<%$ ConnectionStrings:yourConnectionString %>"
SelectCommand="declare @maxNum integer;SET @maxNum=(SELECT MAX(obs_num) FROM Observations); SELECT DISTINCT TOP 15 * FROM Observations WHERE reviewed=1 AND obs_num<=@maxNum-(15*(@pageNum-1)) ORDER BY obs_num DESC">
<SelectParameters>
<asp:SessionParameter Name="pageNum" Type="int32" SessionField="pageNum" />
</SelectParameters>
</asp:SqlDataSource>
This can easily be adpated to use querystring parameters instead of session.
Simple, efficient solution... If you know your way around ajax and sql...
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
I'll always mark your post(s) as answer when it is!