关闭

分页显示DataGrid

678人阅读 评论(1) 收藏 举报

这是我在工作中遇到过的。可能大家觉得很简单,但我还是发表出来。大家如果有什么更好的方法,请给我留言。

private void BindGrid()
  {
   string str = "select * from toplist where [type] = 5";
   DataTable dt=Kubao.CommonPrj.DBA.SQL.LoadDataTable(Kubao.cls_ClassLib.Conn_Mov,str);
   DataView dataview = new DataView();
   dataview=dt.DefaultView;
   DataGrid1.DataSource = dt.DefaultView;
   DataGrid1.DataBind();
  
   string cPage;
   int pageSize = 2;
   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();

   //生成页导航条
   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() +" 页";
  }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32935次
    • 积分:479
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:24篇
    • 译文:0篇
    • 评论:7条
    最新评论