News Ticker

Menu

Paging trong Datalist Asp.net

(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.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube




Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



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 string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataSet FillTable(string sql)
        {
            try
            {
                DataSet tb = new DataSet();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}

VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace PagingDatalist

    Public Class SqlDataProvider

#Region "Membres Prives"

        Shared _IsError As Boolean = False
        Private _connectionString As String

#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() As String
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public Function FillTable(ByVal sql As String) As DataSet
            Try
                Dim tb As New DataSet
                Dim adap As New 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;
}

B4: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page Title="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">
                <tr id="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
<%@ Page Title="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">
                <tr id="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 void BindProduct()
        {
            DataSet objBind = new DataSet();
            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 (int i = 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 DataSet BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataSet objBind = objSQL.FillTable("Select Products.* From Products");
            return objBind;
        }

        #endregion

        #region "Event Handles"

        protected void Page_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 Sub BindProduct()
            Dim objBind As New DataSet
            objBind = BindData()

            If Not objBind Is Nothing Then
                Dim pgd As New 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 As Exception
                        pgd.CurrentPageIndex = 1
                    End Try
                End If

                If pgd.PageCount > 1 Then
                    pnlPaging.Visible = True
                    lnkNext.Enabled = Not pgd.IsLastPage
                    If lnkNext.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 As String = ""
                    For i As Integer = 1 To pgd.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 Not pgd 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 Function BindData() 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 Sub Page_Load(ByVal sender As Object, 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

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



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

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Paging trong Datalist Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM