News Ticker

Menu

Sử dụng AJAX Slider Extender cho Paging Datalist trong Asp.net

(Tạo Paging Datalist bằng AJAX Slider Extender) – Có nhiều cách để phân trang cho Datalist như sử dụng chức năng có sẵn trong Datalist hoặc xây dựng Control riêng để xử lý công việc này. Để có thêm lựa chọn trong việc phân trang cho Datalist, hôm nay thủ thuật lập trình sẽ giới thiệu với các bạn 1 cách nữa, đó là sử dụng AJAX Slider Extender.

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




Nghe những bài hát đỉnh nhất về Thấy cô giáo - 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 PagingDatalistUsingSliderExtender
{
    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 PagingDatalistUsingSliderExtender

    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

B4: Download thư viện AjaxControlToolkit tại địa chỉ: Download

B5: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.

B6: Download các file ảnh tại đây, Copy các ảnh vào thư mục Images của Project.

B7: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ Page Title="Paging in Datalist using AJAX SliderExtender in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PagingDatalistUsingSliderExtender._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods = "true" runat="server">
    </asp:ScriptManager>
    <h3>
        Paging in Datalist using AJAX SliderExtender 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%" OnItemCommand="dlObject_ItemCommand">
                            <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>
                            <FooterTemplate>
                                <asp:Panel ID="pnlPaging" runat="server" HorizontalAlign="Center" visible="false">
                                       <table id="tblPaging" border="0" cellpadding="0" cellspacing="0" width="100%" runat="server">
                                        <tr>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdFirst" runat="server" CommandName="First" ImageUrl="~/Images/first.gif" />
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdPrev" runat="server" CommandName="Prev" ImageUrl="~/Images/Prev.gif" />
                                            </td>
                                            <td align="center" style="width: 150px;">
                                                <asp:TextBox ID="txtSlider" runat="server" AutoPostBack="True" OnTextChanged="txtSlider_Changed" Width="200px"></asp:TextBox>
                                                <cc1:SliderExtender ID="ucSliderExtender" runat="server" Orientation="Horizontal" TargetControlID="txtSlider" Minimum="1"></cc1:SliderExtender>
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdNext" runat="server" CommandName="Next" ImageUrl="~/Images/next.gif" />
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdLast" runat="server" CommandName="Last" ImageUrl="~/Images/last.gif" />
                                            </td>
                                            <td align="right" style="padding-right: 25px" class="PageNumber">
                                                <asp:Label ID="lblPage" runat="server" />
                                            </td>
                                        </tr>
                                    </table>
                                </asp:Panel>
                            </FooterTemplate>
                        </asp:DataList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B7: Viết Code cho file Default.aspx
C# Code
//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;
using AjaxControlToolkit;

namespace PagingDatalistUsingSliderExtender
{
    public partial class _Default : System.Web.UI.Page
    {
        #region "Private Members"

        private PagedDataSource pgd = new PagedDataSource();
        private int PageSize = 20;

        #endregion

        #region "Properties"

        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;

                if (objPage == null)
                {
                    _CurrentPage = 0;
                }
                else
                {
                    _CurrentPage = Convert.ToInt32(objPage);
                }
                return _CurrentPage;
            }

            set { ViewState["_CurrentPage"] = value; }
        }

        #endregion

        #region "Bind Data"

        private void SetPageData()
        {
            DataSet objBind = new DataSet();
            objBind = BindData();
            if (objBind != null)
            {
                pgd.AllowPaging = true;
                pgd.DataSource = objBind.Tables[0].DefaultView;
                pgd.PageSize = PageSize;
            }
        }

        private void BindProduct()
        {
            DataSet objBind = new DataSet();
            objBind = BindData();
            SetPageData();

            if (objBind != null)
            {
                if (pgd.Count > 0)
                {
                    dlObject.DataSource = pgd;
                    dlObject.DataBind();
                    trMessage.Visible = false;
                    dlObject.Visible = true;
                    Panel pnlPaging = dlObject.Controls[dlObject.Controls.Count - 1].FindControl("pnlPaging") as Panel;
                    if (pnlPaging != null)
                    {
                        if (objBind.Tables[0].Rows.Count > pgd.PageSize)
                        {
                            pnlPaging.Visible = true;
                        }
                        else
                        {
                            pnlPaging.Visible = false;
                        }
                    }
                }
                else
                {
                    trMessage.Visible = true;
                    dlObject.Visible = false;
                    lblMessage.Text = "No Data";
                }
                updatePanel.Update();

                TextBox txtSlider = dlObject.Controls[dlObject.Controls.Count - 1].FindControl("txtSlider") as TextBox;
                txtSlider.Text = (pgd.CurrentPageIndex + 1).ToString();

                AjaxControlToolkit.SliderExtender ucSliderExtender = dlObject.Controls[dlObject.Controls.Count - 1].FindControl("ucSliderExtender") as SliderExtender;
                ucSliderExtender.Steps = pgd.PageCount;
                ucSliderExtender.Maximum = pgd.PageCount;

                Label lblPage = dlObject.Controls[dlObject.Controls.Count - 1].FindControl("lblPage") as Label;
                int PageIndex = pgd.CurrentPageIndex + 1;
                lblPage.Text = "Page " + PageIndex + " of " + pgd.PageCount;
            }
        }

        private DataSet BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataSet objBind = objSQL.FillTable("Select Products.* From Products");
            return objBind;
        }

        #endregion

        #region "Datalist Methods"

        protected void dlObject_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
        {
            SetPageData();
            pgd.CurrentPageIndex = CurrentPage;

            if (e.CommandName == "First")
            {
                CurrentPage = 0;
                pgd.CurrentPageIndex = 0;
            }
            else if (e.CommandName == "Prev")
            {
                CurrentPage -= 1;
                if (pgd.CurrentPageIndex > 0)
                {
                    pgd.CurrentPageIndex = pgd.CurrentPageIndex - 1;
                }
            }
            else if (e.CommandName == "Next")
            {
                CurrentPage += 1;
                if (pgd.CurrentPageIndex < pgd.PageCount - 1)
                {
                    pgd.CurrentPageIndex = pgd.CurrentPageIndex + 1;
                }
            }
            else if (e.CommandName == "Last")
            {
                CurrentPage = pgd.PageCount - 1;
                pgd.CurrentPageIndex = pgd.PageCount - 1;
            }
            BindProduct();
        }

        protected void txtSlider_Changed(object sender, EventArgs e)
        {
            TextBox txtSlider = dlObject.Controls[0].Controls[0].FindControl("txtSlider") as TextBox;
            PagedDataSource pgd = new PagedDataSource();
            if (txtSlider != null)
            {
                pgd.CurrentPageIndex = Int32.Parse(txtSlider.Text) - 1;
                BindProduct();
            }
        }

        #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
Imports AjaxControlToolkit

Namespace PagingDatalistUsingSliderExtender

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private pgd As New PagedDataSource
        Private PageSize As Integer = 20

#End Region

#Region "Properties"

        Private Property CurrentPage() As Integer
            Get
                Dim objPage As Object = ViewState("_CurrentPage")
                Dim _CurrentPage As Integer = 0

                If objPage Is Nothing Then
                    _CurrentPage = 0
                Else
                    _CurrentPage = CInt(objPage)
                End If
                Return _CurrentPage
            End Get

            Set(ByVal value As Integer)
                ViewState("_CurrentPage") = value
            End Set
        End Property

#End Region

#Region "Bind Data"

        Private Sub SetPageData()
            Dim objBind As New DataSet
            objBind = BindData()
            If Not objBind Is Nothing Then
                pgd.AllowPaging = True
                pgd.DataSource = objBind.Tables(0).DefaultView
                pgd.PageSize = PageSize
            End If
        End Sub

        Private Sub BindProduct()
            Dim objBind As New DataSet
            objBind = BindData()
            SetPageData()

            If Not objBind Is Nothing Then
                If pgd.Count > 0 Then
                    dlObject.DataSource = pgd
                    dlObject.DataBind()
                    trMessage.Visible = False
                    dlObject.Visible = True
                    Dim pnlPaging As Panel = dlObject.Controls(dlObject.Controls.Count - 1).FindControl("pnlPaging")
                    If Not pnlPaging Is Nothing Then
                        If objBind.Tables(0).Rows.Count > pgd.PageSize Then
                            pnlPaging.Visible = True
                        Else
                            pnlPaging.Visible = False
                        End If
                    End If
                Else
                    trMessage.Visible = True
                    dlObject.Visible = False
                    lblMessage.Text = "No Data"
                End If
                updatePanel.Update()

                Dim txtSlider As TextBox = dlObject.Controls(dlObject.Controls.Count - 1).FindControl("txtSlider")
                txtSlider.Text = pgd.CurrentPageIndex + 1

                Dim ucSliderExtender As AjaxControlToolkit.SliderExtender = dlObject.Controls(dlObject.Controls.Count - 1).FindControl("ucSliderExtender")
                ucSliderExtender.Steps = pgd.PageCount
                ucSliderExtender.Maximum = pgd.PageCount

                Dim lblPage As Label = dlObject.Controls(dlObject.Controls.Count - 1).FindControl("lblPage")
                lblPage.Text = "Page " & pgd.CurrentPageIndex + 1 & " of " & pgd.PageCount
            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 "Datalist Methods"

        Private Sub dlObject_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dlObject.ItemCommand
            SetPageData()
            pgd.CurrentPageIndex = CurrentPage

            If e.CommandName = "First" Then
                CurrentPage = 0
                pgd.CurrentPageIndex = 0
            ElseIf e.CommandName = "Prev" Then
                CurrentPage -= 1
                If pgd.CurrentPageIndex > 0 Then
                    pgd.CurrentPageIndex = pgd.CurrentPageIndex - 1
                End If
            ElseIf e.CommandName = "Next" Then
                CurrentPage += 1
                If pgd.CurrentPageIndex < pgd.PageCount - 1 Then
                    pgd.CurrentPageIndex = pgd.CurrentPageIndex + 1
                End If
            ElseIf e.CommandName = "Last" Then
                CurrentPage = pgd.PageCount - 1
                pgd.CurrentPageIndex = pgd.PageCount - 1
            End If
            BindProduct()
        End Sub

        Protected Sub txtSlider_Changed(ByVal sender As Object, ByVal e As EventArgs)
            Dim txtSlider As TextBox = dlObject.Controls(0).Controls(0).FindControl("txtSlider")
            Dim pgd As New PagedDataSource
            If Not txtSlider Is Nothing Then
                pgd.CurrentPageIndex = Int32.Parse(txtSlider.Text) - 1
                BindProduct()
            End If
        End Sub

#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

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

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



Chúc các bạn thành công!

Quang Bình

Share This:

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 " Sử dụng AJAX Slider Extender cho Paging Datalist trong 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