Có nhiều cách làm, mình sẽ trình bày cách đơn giản nhất là dùng PageDataSource để phân trang, cách làm như sau :
Khởi tạo PageDataSource : PageDataSource page = new PageDataSource ();//có thể dùng biến toàn cục hoặc cục bộ
và khai báo biến toàn cục public static int currentPage=0;//số trang hiện hành
Lưu ý : Cách viết sau dùng source code và lấy dữ liệu bằng dataset. Mình sẽ post toàn bài như sau :
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class PhanTrangForDataList : System.Web.UI.Page
{
PagedDataSource page = new PagedDataSource();//Biến toàn cục
public static int currentpage = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
currentpage = 0;
bind();
}
}
public void bind()
{
PagedDataSource page = new PagedDataSource();//Biến cục bộ
page.AllowPaging = true;//Cho phép phân trang
DataSet ds = GetdataSet();
if (ds.Tables[0].Rows.Count != 0)
{
page.DataSource = ds.Tables[0].DefaultView;
page.PageSize = 5;
page.CurrentPageIndex = currentpage;
link_Next.Visible = true;
link_last.Visible = true;
link_last.Enabled = !page.IsFirstPage;
link_Next.Enabled = !page.IsLastPage;
DataList1.DataSource = page;
DataList1.DataBind();
}
}
public DataSet GetdataSet()
{
SqlConnection connect = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
connect.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from tblSanPham", connect);
da.Fill(ds);
return ds;
}
protected void link_Next_Click(object sender, EventArgs e)
{
currentpage += 1;
bind();
}
protected void link_last_Click(object sender, EventArgs e)
{
currentpage -= 1;
bind();
}
}
Vậy trường hợp nào dùng SqlDataSource, bạn thay đổi Source cho page.DataSource=SlqDataSource là được.
Tôi khuyên các bạn đừng nên dùng control này quá nhiều trong bài làm của mình. SqlDataSource dễ thao tác tay nhưng khó quản lý dữ liệu chưa kể đến có lúc nào đó bạn phải xóa chúng và thao tác lại rất mất thì giờ. Nếu bạn muốn nhanh tay hơn thì vài dòng code cho GetData không mất thời gian của bạn đâu.
Phân trang cho GridView cũng tương tự nếu dùng code
Tôi thích dùng code để lấy dữ liệu hơn là dùng SqlDataSource thao tác bằng tay vì dữ liệu tôi dễ quản lý hơn và không phải thao tác lại nhiều lần trên bài.
share file demo : http://www.mediafire.com/?4yg6me872a5jitr
Chúc thành công nha!!