(Paging in datalist in asp.net) – Phân trang là kỹ thuật đã quá quen thuộc những ai đã và đang viết web. Việc phân trang sẽ giúp cho ứng dụng của bạn tải dữ liệu nhanh và thao tác nhanh hơn. Nếu như Gridview có hỗ trợ chức năng phân trang thì Datalist không có chức năng này. Vậy có cách nào để tự bổ xung thêm chức năng phân trang cho Datalist không? Bài viết dưới đây sẽ hướng dẫn các bạn thêm Control Paging cho Datalist.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- B2: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace PagingDatalist
{
public class SqlDataProvider
{
#region"Membres Prives"
private string_connectionString;
#endregion
#region"Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region"Proprietes"
public stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataSetFillTable(string sql)
{
try
{
DataSet tb = newDataSet();
SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace PagingDatalist
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString AsString
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() AsString
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public FunctionFillTable(ByVal sql AsString) As DataSet
Try
Dim tb AsNew DataSet
Dim adap AsNew SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B3: Mở file Site.css bổ xung thêm đoạn mã dưới
.paging_active
{
display: inline-block;
height: 25px;
min-width: 25px;
line-height: 25px;
text-align: center;
text-decoration: none;
border: 1px solid #ccc;
margin:2px;
background-color: #6C6C6C;
color: #fff !important;
}
.paging
{
display: inline-block;
height: 25px;
min-width: 25px;
line-height: 25px;
text-align: center;
text-decoration: none;
border: 1px solid #ccc;
margin:2px;
background-color: #eee;
color: #000;
}C#
<%@ PageTitle="Paging Datalist in ASP.NET" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PagingDatalist._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
</asp:ScriptManager>
<h3>
Paging Datalist in ASP.NET
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%"style="BORDER-COLLAPSE: collapse" borderColor="#cccccc" border="1">
<trid="trMessage"runat="server"visible="false">
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DataList ID="dlObject" runat="server" DataKeyField="ProductID" Width="100%">
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<ItemStyle CssClass="GridStyle_RowStyle"/>
<HeaderTemplate>
<table cellpadding="0"cellspacing="0"width="100%">
<tr>
<th align="center"width="200px">ProductName</th>
<th align="center"width="100px">QuantityPerUnit</th>
<th align="center"width="80px">UnitPrice</th>
<th align="center"width="80px">UnitsInStock</th>
<th align="center"width="80px">UnitsOnOrder</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td align="left"width="200px">
<asp:Label ID="lblProductID"runat="server"Visible="false"Text='<%# Eval("ProductID") %>' />
<asp:Label ID="lblProductName"Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
</td>
<td align="left"width="100px">
<asp:Label ID="lblQuantityPerUnit"Text='<%# Eval("QuantityPerUnit") %>' runat="server"></asp:Label>
</td>
<td align="right"width="80px">
<asp:Label ID="lblUnitPrice"Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
</td>
<td align="right"width="80px">
<asp:Label ID="lblUnitsInStock"Text='<%# Eval("UnitsInStock") %>' runat="server"></asp:Label>
</td>
<td align="right"width="80px">
<asp:Label ID="lblUnitsOnOrder"Text='<%# Eval("UnitsOnOrder") %>' runat="server"></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
<tr>
<td>
<asp:Panel ID="pnlPaging" Runat="server" HorizontalAlign="Center" visible="false">
<asp:HyperLink ID="lnkPrev" Runat="server" CssClass="CommandButton"><span class="paging"><<</span></asp:HyperLink>
<asp:label id="lblCurrentPage" runat="server"></asp:label>
<asp:HyperLink ID="lnkNext" Runat="server" CssClass="CommandButton"><span class="paging">>></span></asp:HyperLink>
</asp:Panel>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>VB.Net Code
<%@ PageTitle="Paging Datalist in ASP.NET" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"Inherits="PagingDatalist._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
</asp:ScriptManager>
<h3>
Paging Datalist in ASP.NET
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%"style="BORDER-COLLAPSE: collapse" borderColor="#cccccc" border="1">
<trid="trMessage"runat="server"visible="false">
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DataList ID="dlObject" runat="server" DataKeyField="ProductID" Width="100%">
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<ItemStyle CssClass="GridStyle_RowStyle"/>
<HeaderTemplate>
<table cellpadding="0"cellspacing="0"width="100%">
<tr>
<th align="center"width="200px">ProductName</th>
<th align="center"width="100px">QuantityPerUnit</th>
<th align="center"width="80px">UnitPrice</th>
<th align="center"width="80px">UnitsInStock</th>
<th align="center" width="80px">UnitsOnOrder</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td align="left"width="200px">
<asp:Label ID="lblProductID"runat="server"Visible="false"Text='<%# Eval("ProductID") %>' />
<asp:Label ID="lblProductName"Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
</td>
<td align="left"width="100px">
<asp:Label ID="lblQuantityPerUnit"Text='<%# Eval("QuantityPerUnit") %>' runat="server"></asp:Label>
</td>
<td align="right"width="80px">
<asp:Label ID="lblUnitPrice"Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
</td>
<td align="right"width="80px">
<asp:Label ID="lblUnitsInStock"Text='<%# Eval("UnitsInStock") %>' runat="server"></asp:Label>
</td>
<td align="right"width="80px">
<asp:Label ID="lblUnitsOnOrder"Text='<%# Eval("UnitsOnOrder") %>' runat="server"></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
<tr>
<td>
<asp:Panel ID="pnlPaging" Runat="server" HorizontalAlign="Center" visible="false">
<asp:HyperLink ID="lnkPrev" Runat="server" CssClass="CommandButton"><span class="paging"><<</span></asp:HyperLink>
<asp:label id="lblCurrentPage" runat="server"></asp:label>
<asp:HyperLink ID="lnkNext" Runat="server" CssClass="CommandButton"><span class="paging">>></span></asp:HyperLink>
</asp:Panel>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B5: Viết Code cho file Default.aspx
C#
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
namespace PagingDatalist
{
public partial class _Default : System.Web.UI.Page
{
#region"Bind Data"
private voidBindProduct()
{
DataSet objBind = newDataSet();
objBind = BindData();
if (objBind != null)
{
PagedDataSource pgd = new PagedDataSource();
pgd.AllowPaging = true;
pgd.DataSource = objBind.Tables[0].DefaultView;
pgd.PageSize = 15;
if (!string.IsNullOrEmpty(Request["Page"]))
{
{
pgd.CurrentPageIndex = Convert.ToInt32(Request["Page"]);
}
}
if (pgd.PageCount > 1)
{
pnlPaging.Visible = true;
lnkNext.Enabled = !pgd.IsLastPage;
if (lnkNext.Enabled)
{
lnkNext.NavigateUrl = "Default.aspx?Page=" + (pgd.CurrentPageIndex + 1).ToString();
}
lnkPrev.Enabled = !pgd.IsFirstPage;
if (lnkPrev.Enabled)
{
lnkPrev.NavigateUrl = "Default.aspx?Page=" + (pgd.CurrentPageIndex - 1).ToString();
}
string strPages = "";
for (inti = 1; i <= pgd.PageCount; i++)
{
if (i == (pgd.CurrentPageIndex + 1))
{
strPages = strPages + "<span class=\"paging_active\">" + i.ToString() + "</span>";
}
else
{
strPages = strPages + "<a href=Default.aspx?Page="+ (i - 1).ToString() + "><span class=\"paging\">" + i.ToString() + "</span></a>";
}
}
lblCurrentPage.Text = strPages;
}
else
{
pnlPaging.Visible = false;
}
if (pgd != null)
{
if (pgd.Count > 0)
{
dlObject.DataSource = pgd;
dlObject.DataBind();
trMessage.Visible = false;
dlObject.Visible = true;
}
else
{
trMessage.Visible = true;
dlObject.Visible = false;
lblMessage.Text = "No Data";
}
updatePanel.Update();
}
}
}
private DataSetBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataSet objBind = objSQL.FillTable("Select Products.* From Products");
return objBind;
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindProduct();
}
}
catch
{
}
}
#endregion
}
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.Data
Namespace PagingDatalist
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private SubBindProduct()
Dim objBind As New DataSet
objBind = BindData()
If Not objBind Is Nothing Then
Dim pgd AsNew PagedDataSource
pgd.AllowPaging = True
pgd.DataSource = objBind.Tables(0).DefaultView
pgd.PageSize = 15
If Request("Page") <> "" Then
Try
pgd.CurrentPageIndex = Convert.ToInt32(Request("Page"))
Catch ex AsException
pgd.CurrentPageIndex = 1
End Try
End If
If pgd.PageCount > 1 Then
pnlPaging.Visible = True
lnkNext.Enabled = Not pgd.IsLastPage
IflnkNext.Enabled Then
lnkNext.NavigateUrl = "Default.aspx?Page=" & (pgd.CurrentPageIndex + 1).ToString()
End If
lnkPrev.Enabled = Not pgd.IsFirstPage
If lnkPrev.Enabled Then
lnkPrev.NavigateUrl = "Default.aspx?Page=" & (pgd.CurrentPageIndex - 1).ToString()
End If
Dim strPages AsString = ""
For i AsInteger = 1 Topgd.PageCount
If i = (pgd.CurrentPageIndex + 1) Then
strPages = strPages + "<span class=""paging_active"">" & i.ToString() & "</span>"
Else
strPages = strPages + "<a href=Default.aspx?Page="& (i - 1).ToString() & "><span class=""paging"">" & i.ToString() & "</span></a>"
End If
Next
lblCurrentPage.Text = strPages
Else
pnlPaging.Visible = False
End If
If Notpgd Is Nothing Then
If pgd.Count > 0 Then
dlObject.DataSource = pgd
dlObject.DataBind()
trMessage.Visible = False
dlObject.Visible = True
Else
trMessage.Visible = True
dlObject.Visible = False
lblMessage.Text = "No Data"
End If
updatePanel.Update()
End If
End If
End Sub
Private FunctionBindData() As DataSet
Dim objSQL As New SqlDataProvider
Dim objBind As DataSet = objSQL.FillTable("Select Products.* From Products")
Return objBind
End Function
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
BindProduct()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment