(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.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- 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 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
}
}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 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
- 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
<%@ PageTitle="Paging in Datalist using AJAX SliderExtender in ASP.Net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="PagingDatalistUsingSliderExtender._Default"%>
<%@ RegisterAssembly="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">
<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%" 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 PagedDataSourcepgd = new PagedDataSource();
private int PageSize = 20;
#endregion
#region"Properties"
private intCurrentPage
{
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 voidSetPageData()
{
DataSet objBind = newDataSet();
objBind = BindData();
if (objBind != null)
{
pgd.AllowPaging = true;
pgd.DataSource = objBind.Tables[0].DefaultView;
pgd.PageSize = PageSize;
}
}
private voidBindProduct()
{
DataSet objBind = newDataSet();
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") asPanel;
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") asTextBox;
txtSlider.Text = (pgd.CurrentPageIndex + 1).ToString();
AjaxControlToolkit.SliderExtenderucSliderExtender = 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") asLabel;
int PageIndex = pgd.CurrentPageIndex + 1;
lblPage.Text = "Page " + PageIndex + " of " + pgd.PageCount;
}
}
private DataSetBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataSet objBind = objSQL.FillTable("Select Products.* From Products");
return objBind;
}
#endregion
#region"Datalist Methods"
protected voiddlObject_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgse)
{
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 voidtxtSlider_Changed(object sender, EventArgs e)
{
TextBox txtSlider = dlObject.Controls[0].Controls[0].FindControl("txtSlider") asTextBox;
PagedDataSource pgd = newPagedDataSource();
if (txtSlider != null)
{
pgd.CurrentPageIndex = Int32.Parse(txtSlider.Text) - 1;
BindProduct();
}
}
#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
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 PropertyCurrentPage() As Integer
Get
Dim objPage AsObject = ViewState("_CurrentPage")
Dim _CurrentPage As Integer = 0
If objPage IsNothing 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 SubSetPageData()
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 SubBindProduct()
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 AsPanel = dlObject.Controls(dlObject.Controls.Count - 1).FindControl("pnlPaging")
If NotpnlPaging Is NothingThen
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()
DimtxtSlider 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 AsLabel = dlObject.Controls(dlObject.Controls.Count - 1).FindControl("lblPage")
lblPage.Text = "Page "& pgd.CurrentPageIndex + 1 & " of " & pgd.PageCount
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 "Datalist Methods"
Private SubdlObject_ItemCommand(ByVal source As Object, ByVal e AsSystem.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
EndIf
ElseIf e.CommandName = "Last"Then
CurrentPage = pgd.PageCount - 1
pgd.CurrentPageIndex = pgd.PageCount - 1
End If
BindProduct()
End Sub
Protected SubtxtSlider_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 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
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