实现DataGrid的分页
private void BindGrid() {
SqlConnection con=new SqlConnection("server=.;database=Northwind;uid=d;pwd=d;");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter sqlAdapter = new SqlDataAdapter("select * from Customers",con);
sqlAdapter.Fill(ds,"users");
DataView dataview = new DataView();
dataview = ds.Tables[0].DefaultView;
DataGrid1.DataSource = ds.Tables[0].DefaultView;
DataGrid1.DataBind();
string cPage;
int pageSize = 10;
int currentPage;
int pageCount;
int numResults = 0;
if (Request.QueryString["page"]==null)
{
cPage="1";
}
else
{
cPage=Request.QueryString["page"].ToString();
}
try
{
currentPage = Int32.Parse(cPage);
}
catch
{
currentPage = 1;
}
numResults = 0;
int start = (int)((currentPage - 1) * pageSize);
int to = (int)(currentPage * pageSize);
if (start <= 0) start = 0;
numResults = dataview.Count;
int a1=0;
pageCount = Math.DivRem(numResults,pageSize,out a1);
if (a1>0)
{
pageCount++;
}
if(currentPage>pageCount || currentPage<=0)
{
currentPage = 1;
}
if(currentPage==pageCount)
{
to = dataview.Count;
}
// Create one DataTable with one column.
DataTable myTable = new DataTable("myTable");
myTable = dataview.Table.Clone();
//add row
DataRow NewRow;
for(int i=start;i<numResults;i++)
{
if(i<to)
{
NewRow = myTable.NewRow();
for(int k=0;k<dataview.Table.Columns.Count;k++)
{
NewRow[k] = dataview.Table.Rows[i][k];
}
myTable.Rows.Add(NewRow);
}
}
myTable.AcceptChanges();
DataView resultDataview = new DataView(myTable);
DataGrid1.DataSource = resultDataview;
DataGrid1.DataBind();
/// <summary>
/// 生成页导航条。
/// </summary>
string strNav = "";
int endpage;
if (currentPage>1)
{
strNav += "<a href='?page="+ (currentPage-1).ToString() +"'>上一页</a> ";
}
if (currentPage>11)
{
strNav += "<a href='?page=1'>1</a> ...";
}
if(pageCount>currentPage+10)
{
endpage = currentPage+10;
}
else
{
endpage = pageCount;
}
for (int i=currentPage-10;i<endpage+1;i++)
{
if(i>=1)
{
if (i==currentPage)
{
strNav +="<font color=#990000><strong>"+ i.ToString() +"</strong></font> ";
}
else
{
strNav += "<a href='?page="+ i.ToString() +"'>"+ i.ToString() +"</a> ";
}
}
}
if((currentPage+10)<pageCount)
{
strNav += "... <a href='?page="+ pageCount.ToString() +"'>"+ pageCount.ToString() +"</a>";
}
if(currentPage<pageCount)
{
strNav += " <a href='?page="+ (currentPage+1).ToString() +"'>下一页</a> ";
}
Literal1.Text = strNav;
Literal2.Text = "共 "+ numResults.ToString() +" 条供应信息,当前显示第 "+
(start+1).ToString() +" - "+ to.ToString() +" 条,共 "+ pageCount.ToString() +" 页";
}
然后在page_load事件里 写入BindGrid() ;
[此贴子已经被作者于2005-10-17 11:35:54编辑过]