⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 custompaging.aspx

📁 asp.net经典案例资料
💻 ASPX
字号:
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>
  <head>
    <title>DataGrid的自定义分页</title>
    <script language="C#" runat="server" >

    // Public variables
    const int PageSize = 5;
    int PageCount;
    int currentPageIndex;
    DataSet dataSet;

    // Current Page Index must be maintained by ViewState
    public int CurrentPageIndex {
      get {
        object o = ViewState["CurrentPageIndex"];
        return((o == null) ? 0 : (int)o);
      }
      set { ViewState["CurrentPageIndex"] = value; }
    }

    // the first and last primary key of the container
    public string LastKey {
      get {
        object o = ViewState["LastKey"];
        return((o == null) ? String.Empty : (string)o);
      }
      set { ViewState["LastKey"] = value; }
    }
    public string FirstKey {
      get {
        object o = ViewState["FirstKey"];
        return((o == null) ? String.Empty : (string)o);
      }
      set { ViewState["FirstKey"] = value; }
    }

    public void GetNextPrevPage(string direction) {
      string dataSource = "Data Source=localhost;";
      string security = "user id=sa; password=;";
      string initialCatalog = "initial catalog=pubs;";
      string cnnString = dataSource + security + initialCatalog;
      SqlConnection connection = new SqlConnection(cnnString);

      try {
        connection.Open();

        // Get total item count and PageCount
        SqlCommand command = new SqlCommand("select count(*) from authors", connection);
        int totalItemNumber = (int)command.ExecuteScalar();
        PageCount = ( totalItemNumber % PageSize == 0 ) ? 
          totalItemNumber/PageSize : totalItemNumber/PageSize + 1;

        // Fill dataset by search forward and backward
        string strSql =  " select top " + PageSize.ToString();
        strSql += " au_id, au_lname, au_fname, city, state, zip from authors";
        if( direction == "Next" )
          strSql += " where au_id > '" + LastKey + "' order by au_id";
        else
          strSql += " where au_id < '" + FirstKey + "' order by au_id desc";
        command = new SqlCommand(strSql, connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;
        dataSet = new DataSet();
        adapter.Fill(dataSet);

        // Calculate page index.
        DataTable tmpTable = dataSet.Tables[0];
        if( tmpTable.Rows.Count == 0 ){
          if(direction == "Next")
            GetPageByNumber(PageCount);
          else
            GetPageByNumber(1);
          return;
        }
        else {
          if(direction == "Next") {
            CurrentPageIndex ++;
            if(CurrentPageIndex > PageCount)
              CurrentPageIndex = PageCount;
          }
          else {
            CurrentPageIndex --;
            if(CurrentPageIndex < 1)
              CurrentPageIndex = 1;
          }
        }

        // Record lastkey and first key
        if(direction == "Next") {
          FirstKey = (string)tmpTable.Rows[0]["au_id"];
          LastKey  = (string)tmpTable.Rows[ tmpTable.Rows.Count-1 ]["au_id"];
        }
        else {
          LastKey = (string)tmpTable.Rows[0]["au_id"];
          FirstKey  = (string)tmpTable.Rows[ tmpTable.Rows.Count-1 ]["au_id"];
        }
      }
      catch(SqlException e) {
        Response.Write(e.ToString());
        return;
      } 
      finally {
        connection.Close();
      }
    }

    public void GetPageByNumber(int pageNo) {
      string dataSource = "Data Source=localhost;";
      string security = "user id=sa; password=;";
      string initialCatalog = "initial catalog=pubs;";
      string cnnString = dataSource + security + initialCatalog;
      SqlConnection connection = new SqlConnection(cnnString);

      try {
        connection.Open();

        // Get total item count and PageCount
        SqlCommand command = new SqlCommand("select count(*) from authors", connection);
        int totalItemNumber = (int)command.ExecuteScalar();
        PageCount = ( totalItemNumber % PageSize == 0 ) ? 
          totalItemNumber/PageSize : totalItemNumber/PageSize + 1;

        // Calculate current page index
        if(pageNo < 1)
          CurrentPageIndex = 1;
        else if(pageNo > PageCount)
          CurrentPageIndex = PageCount;
        else
          CurrentPageIndex = pageNo;

        // Get data to the dataset
        string strSql =  " select au_id, au_lname, au_fname, city, state, zip from [authors]";
        strSql += " order by au_id";
        command = new SqlCommand(strSql, connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;
        int startIndex = (CurrentPageIndex -1 ) * PageSize;
        dataSet = new DataSet();
        adapter.Fill(dataSet, startIndex, PageSize, "Authors");

        // Record lastkey and first key
        DataTable tmpTable = dataSet.Tables[0];
        FirstKey = (string)tmpTable.Rows[0]["au_id"];
        LastKey  = (string)tmpTable.Rows[ tmpTable.Rows.Count-1 ]["au_id"];
      }
      catch( SqlException e) {
        Response.Write(e.ToString());
        return;
      }
      finally {
        connection.Close();
      }
    }

    public void BindGrid() {
      DataView dataView = dataSet.Tables[0].DefaultView;
      dataView.Sort = "au_id";
      grid1.DataSource = dataView;
      grid1.DataBind();
      txtCurrentPageIndex.Text = CurrentPageIndex.ToString();
      lblPageCount.Text = PageCount.ToString();
    }

    public void Page_Load() {
      if(!IsPostBack) {
        CurrentPageIndex = 1;
        GetPageByNumber(CurrentPageIndex);
        BindGrid();
      }
    }

    public void NextPrevPage(object sender, EventArgs e) {
      if(((LinkButton)sender).ID == "PrevButton")
        GetNextPrevPage("Prev");
      else
        GetNextPrevPage("Next");
      BindGrid();
    }

    public void JumpToPage(object sender, EventArgs e) {
      int number = 0;
      try { 
        number = int.Parse(txtCurrentPageIndex.Text); 
      }
      catch { 
        txtCurrentPageIndex.Text = CurrentPageIndex.ToString();
        return;
      }
      GetPageByNumber(number);
      BindGrid();
    }
    </script>
  </head>

  <body>
  <form id="form1" runat="server">
    <h3>DataGrid的自定义分页</h3>
    <asp:DataGrid id="grid1" runat="server" >
        <HeaderStyle BackColor="lightblue" Font-Name="Arial" Font-Bold="true" />
        <ItemStyle BackColor="lightyellow"/>
    </asp:DataGrid>
    <asp:LinkButton Text="上一页" id="PrevButton" OnClick="NextPrevPage" runat="server" />
    <asp:LinkButton Text="下一页" id="NextButton" OnClick="NextPrevPage" runat="server" />
    &nbsp;跳转到 <asp:TextBox id="txtCurrentPageIndex" width="20pt" 
      OnTextChanged="JumpToPage" AutoPostBack="true" runat="server"/>页,
    &nbsp;总共<asp:Label id="lblPageCount" runat="server"/>页
  </form>
  </body>
</html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -