關於msdn上面的《Web 窗體頁創建分頁的數據訪問》的改進

   前段時間做了第一個ASP.NET項目,很簡單的。在DataGrid分頁的時候遇到小問題,就參考msdn的例子做了一個。實際過程中發現似乎有點問題,改進了一下:

   鏈接:ms-help://MS.MSDNQTR.2003FEB.2052/vbcon/html/vbwlkwalkthroughdisplayingdatainlistboxesonwebformspage.htm

   說明:該文章使用了兩個sql語句,目的是向前翻頁的時候和向後翻頁的時候分別使用不同的語句。改進以後只用一條語句就可以。我在項目裏面使用的是存儲過程:
   CREATE PROCEDURE selectAllUser
   (
      @Id int
   )
    AS
   select top 15 Id,UserName,IDcard,Sex,Birthday,MailAddr,GetscholarTime
   from UserInfo
   where  Id>=@Id
   GO

   關鍵代碼如下:
   ///
   /// 從數據庫讀取從userID開始的15條記錄並顯示
   ///
   ///
  private void showAllUser(int userID)
  {
      ManageDB managedb = new ManageDB();
      int count = managedb.getUserCount();   //這個方法獲取總記錄數
      if(count == -1)
   {
       Response.Redirect("error.aspx",true);
       return;
   }
      count = count/this.gridUser.PageSize;
      SqlDataReader reader = managedb.getAllUser(userID);
      this.gridUser.DataSource = reader;
      this.gridUser.DataBind();
      reader.Close();
      ViewState["CurrentPage"] = CurrentPage;
      ViewState[CurrentPage.ToString()] = this.gridUser.Items[0].Cells[0].Text;
      if(CurrentPage <=0)
      {
          this.btnPrevious.Enabled = false;
      }
      if(CurrentPage >= count)
      {
          this.btnNext.Enabled = false;
      }
  }

   下一頁按鈕點擊事件:
   private void btnNext_Click(object sender, System.EventArgs e)
  {
      this.btnPrevious.Enabled = true;
      CurrentPage = (int)(ViewState["CurrentPage"]);
      CurrentPage ++;
      //下面的代碼有個+1操作,這個是必須的,這樣保證了取得的記錄沒有重複的。
      int lastID = Convert.ToInt32(this.gridUser.Items[this.gridUser.PageSize-1].Cells[0].Text) + 1;
      this.showAllUser(lastID);
    }

   上一頁按鈕點擊事件
   private void btnPrevious_Click(object sender, System.EventArgs e)
  {
      this.btnNext.Enabled = true;
      CurrentPage = Convert.ToInt32(ViewState["CurrentPage"]);
      CurrentPage--;
      if (CurrentPage >= 0) 
      {
          int firstid;
          firstid = Convert.ToInt32(ViewState[(CurrentPage).ToString()]);
          this.showAllUser(firstid);
      }
   }

   最後是page load事件裏面添加:

   if(!Page.IsPostBack)
   {
       CurrentPage = 0;
       this.showAllUser(0);
   }

   這樣就對一個簡單的分頁改進了一下。當然我們還可以顯示出總頁數,當前頁數。但是這種分頁功能不強,不能做到直接跳轉到第幾頁。但是這個分頁效率可以說是相當高的。

   整個源代碼可以這裏下載,注意數據庫是sql server2000。
   另外我的Blog最近將推出.net書籍以及源代碼下載,請關注!
 

發佈了11 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章