public partial class fenye :System.Web.UI.Page
{
//声明一变量,用来存储每页记录数
intpagesize = 10;
protectedvoid Page_Load(objectsender, EventArgs e)
{
if(!IsPostBack)
{
//此变量用来存储页码,岁服务器发送到客户端,岁客户端发送到服务器,其中的值不会因为页面重新加载而回复默认值
ViewState["pageindex"] = "1";
GetXzqh();
}
}
protectedvoid btnfirst_Click(objectsender, EventArgs e)
{
//用户点击首页按钮,将当前页面更改为页
ViewState["pageindex"]= "1";
GetXzqh();
}
protectedvoid btnpre_Click(objectsender, EventArgs e)
{
intpageindex = Convert.ToInt32(ViewState["pageindex"]);
//当当前页码时,页码就不再变化
if(pageindex > 1)
{
pageindex--;
}
ViewState["pageindex"]= pageindex.ToString();
GetXzqh();
}
protectedvoid btnnext_Click(objectsender, EventArgs e)
{
intpageindex = Convert.ToInt32(ViewState["pageindex"]);
//当当前页码总页数时最大页码时,页码就不再变化
if(pageindex < GetTotalSize())
{
pageindex++;
}
ViewState["pageindex"]= pageindex.ToString();
GetXzqh();
}
protectedvoid btnlast_Click(objectsender, EventArgs e)
{
//用户点击“尾页”按钮,将当前页码设置最大页码
ViewState["pageindex"]= GetTotalSize();
GetXzqh();
}
//获取总页数
privateint GetTotalSize()
{
stringstrcon = @"Data Source=YHB-PC;InitialCatalog=MyTest;Persist Security Info=True;User ID=sa;Password=yhb@163";
SqlConnectioncnn = new SqlConnection(strcon);
SqlCommandcmm = new SqlCommand();
cmm.Connection = cnn;
cnn.Open();
cmm.CommandText = "select count(*) from T_Xzqh";
objectobj = cmm.ExecuteScalar();
if(obj != null)
{
inttotal = Convert.ToInt32(obj);
//计算的最大页码
if(total % pagesize == 0)
{
returntotal / pagesize;
}
else
{
returntotal / pagesize + 1;
}
}
cmm.Dispose();
cnn.Dispose();
return0;
}
privatevoid GetXzqh()
{
stringstrcon = @"Data Source=YHB-PC;InitialCatalog=MyTest;Persist Security Info=True;User ID=sa;Password=yhb@163";
SqlConnectioncnn = new SqlConnection(strcon);
SqlCommandcmm = new SqlCommand();
cmm.Connection = cnn;
//值为存储过程名称
cmm.CommandText = "procfenye";
//使º1用®?枚?举¨´表À¨ª明¡ÂSqlCommand对象发送的是存储过程而不是sql语句,若执行的是语句应将cmm.CommandType设置成CommandType.Text或者不做设置其认值就为CommandType.Text
cmm.CommandType = CommandType.StoredProcedure;
cmm.Parameters.AddWithValue("@pageindex", Convert.ToInt32(ViewState["pageindex"]));
cmm.Parameters.AddWithValue("@pagesize", pagesize);
SqlDataAdapteradapter = new SqlDataAdapter(cmm);
DataTabledt = new DataTable();
adapter.Fill(dt);
this.GridView1.DataSource= dt;
this.GridView1.DataBind();
//记住释放数据库连接资源
cmm.Dispose();
cnn.Dispose();
}
}