以下是我的版本,刚才网页有错误所以删除重新发了一下,很郁闷,CSDN博客确实不怎么样,注释不想再写了,大家如果有疑问或者有好的建议请联系我^_^
主要是进行了一些优化:组件化,使用属性,一些不知道原因的错误,改成了适合自己的数据源对象,还有原先代码的一点小的疏忽^_^
using System;
using System.Data;
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;
using System.Data;
using System.Data.SqlClient;
public partial class myUserControl : System.Web.UI.UserControl
{
SqlConnection conn;
int RecordCount, PageCount, CurrentPage;
private int PageSize;
public int _PageSize
{
get {
return PageSize;
}
set {
PageSize = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WroxUnited"].ConnectionString);
conn.Open();
if (!Page.IsPostBack)
{
CurrentPage = 0;
ViewState["PageIndex"] = 0;
ListBind();
RecordCount = CalculateRecord();
if(RecordCount%PageSize==0)
PageCount = RecordCount / PageSize;
else
PageCount = RecordCount / PageSize+1;
ViewState["PageCount"] = PageCount;
}
}
public int CalculateRecord()
{
int intCount;
string strCount = "SELECT COUNT(*) AS co FROM Players";
SqlCommand comm = new SqlCommand(strCount, conn);
SqlDataReader dr = comm.ExecuteReader();
if (dr.Read())
{
intCount = Int32.Parse(dr["co"].ToString());
}
else
{
intCount = 0;
}
dr.Close();
return intCount;
}
ICollection CreateSource()
{
int StartIndex;
//设定导入的起终地址
StartIndex = CurrentPage * PageSize;
string strSel = "SELECT FirstName FROM Players";
DataSet ds = new DataSet();
SqlDataAdapter MyAdapter = new SqlDataAdapter(strSel, conn);
MyAdapter.Fill(ds, StartIndex, PageSize, "Players");
return ds.Tables["Players"].DefaultView;
}
public void ListBind()
{
score.DataSource = CreateSource();
score.DataBind();
if (CurrentPage == (PageCount - 1)) LinkButton2.Enabled = false;
if (CurrentPage == 0) LinkButton1.Enabled = false;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
CurrentPage = (int)ViewState["PageIndex"];
PageCount = (int)ViewState["PageCount"];
if (CurrentPage > 0) CurrentPage--;
ViewState["PageIndex"] = CurrentPage;
ListBind();
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
CurrentPage = (int)ViewState["PageIndex"];
PageCount = (int)ViewState["PageCount"];
if (CurrentPage < (PageCount - 1)) CurrentPage++;
ViewState["PageIndex"] = CurrentPage;
ListBind();
}
}
既然是控件,那么一定要有调用的页面,如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="11111111.aspx.cs" Inherits="_11111111" %>
<%@ Register Src="myUserControl.ascx" TagName="myUserControl" TagPrefix="uc1" %>
<!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>
<uc1:myUserControl id="MyUserControl1" runat="server" _PageSize="5"></uc1:myUserControl></div>
</form>
</body>
</html>