using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
PagedDataSource pds = new PagedDataSource();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
doPaging();
}
/// <summary>
/// 获取要显示在DataList里的数据
/// </summary>
/// <returns></returns>
private DataTable getData()
{
string strCon = "server=.; database=northwind; uid=sa; pwd=sa";
SqlConnection con = new SqlConnection(strCon);
string sqlStr = "select employeeid, lastname, firstname, birthdate, address, City, Country, photopath from employees";
SqlDataAdapter da = new SqlDataAdapter(sqlStr, con);
da.Fill(ds);
return ds.Tables[0];
}
/// <summary>
/// 分页用能
/// </summary>
private void doPaging()
{
pds.DataSource = getData().DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;
try
{
pds.CurrentPageIndex = int.Parse(Request.QueryString["page"]);
}
catch (Exception)
{
pds.CurrentPageIndex = 0;
}
btnPrev.Visible = (!pds.IsFirstPage);
btnNext.Visible = (!pds.IsLastPage);
DataList1.DataSource = pds;
DataList1.DataBind();
}
//上一页
protected void Prev_Click(object sender, EventArgs e)
{
Response.Redirect(Request.CurrentExecutionFilePath+"?page="+(pds.CurrentPageIndex-1));
}
//下一页
protected void Next_Click(object sender, EventArgs e)
{
Response.Redirect(Request.CurrentExecutionFilePath+"?page="+(pds.CurrentPageIndex+1));
}
}
//后台HTML代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="northwindPagedDataSource.aspx.cs" Inherits="northwindPagedDataSource" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="theDataList" runat="server">
<ItemTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="500">
<tr>
<td>
Company Name:</td><td><%# DataBinder.Eval(Container.DataItem,"companyName") %>
Contact Name:</td><td><%# DataBinder.Eval(Container.DataItem,"contactName") %>
Contact Title:</td><td><%# DataBinder.Eval(Container.DataItem,"contactTitle") %>
</td>
</tr>
</table>
</ItemTemplate></asp:DataList>
<asp:LinkButton ID="btnPrev" runat="server" OnClick="Prev_Click" Text="<"></asp:LinkButton>
<asp:LinkButton ID="btnNext" runat="server" OnClick="Next_Click" Text=">"></asp:LinkButton>
</div>
</form>
</body>
</html>
用DataList分页读取数据
最新推荐文章于 2024-09-20 16:06:21 发布