前言:
公司項目開發,上周的任務是做基礎數據的管理。在Sharepoint2010里邊內嵌asp.net的aspx頁,遇到了各種各樣奇葩的問題,因為之前對sharepoint只是有一些了解,但是沒有設計到具體的編程工作,這一次算是初次接觸吧。其中有一部分基礎數據數據量很大,大致有十多萬,因為是對基礎數據的維護,所以還需要對數據進行列表展示,增刪改查什么的,大家都知道Asp.net里邊的GridView有自帶的分頁,但是,那個分頁對於少量的數據還好,對於這種數十萬的數據量而言,這種分頁方式簡直就是災難。網上關於GridView高效分頁的東西有很多,找了一個自己改了改。用着效果還不錯,和大家分享一下。
這是分頁的效果圖
下邊就講一下具體的實現,首先聲明,這個東西是不是我原創的,只是在此基礎上進行了修飾和完善。希望能給各位有所啟發。
一、前台布局
<div> <div id="main"> <div id="search"> <table> <tr> <td> <asp:Label ID="lb" runat="server" Text="姓名"></asp:Label></td> <td> <asp:TextBox ID="SearchName" runat="server"></asp:TextBox> </td> <td> <asp:Button ID="btnSearch" runat="server" Text="查詢" onclick="PagerBtnCommand_OnClick" CommandName="search" /> </td> <td> <asp:Button ID="btnReset" runat="server" Text="重置" onclick="btnReset_Click" /> </td> </tr> </table> </div> <div id="gridView"> <asp:GridView ID="UserGridView" runat="server" AutoGenerateColumns="false"> <Columns> <asp:TemplateField HeaderText="用戶名"> <ItemTemplate> <asp:Label ID="UserName" runat="server" Text='<%#Eval("username") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="單位名稱"> <ItemTemplate> <asp:Label ID="DisplayName" runat="server" Text='<%#Eval("displayname") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="組織編碼"> <ItemTemplate> <asp:Label ID="OrgCode" runat="server" Text='<%#Eval("orgcode") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="組織名稱"> <ItemTemplate> <asp:Label ID="OrgName" runat="server" Text='<%#Eval("orgname") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> <div id="page"> <table> <tr> <td> <asp:Label ID="lbcurrentpage1" runat="server" Text="當前頁:"></asp:Label> <asp:Label ID="lbCurrentPage" runat="server" Text=""></asp:Label> <asp:Label ID="lbFenGe" runat="server" Text="/"></asp:Label> <asp:Label ID="lbPageCount" runat="server" Text=""></asp:Label> </td> <td> <asp:Label ID="recordscount" runat="server" Text="總條數:"></asp:Label> <asp:Label ID="lbRecordCount" runat="server" Text=""></asp:Label> </td> <td> <asp:Button ID="Fistpage" runat="server" CommandName="" Text="首頁" OnClick="PagerBtnCommand_OnClick" /> <asp:Button ID="Prevpage" runat="server" CommandName="prev" Text="上一頁" OnClick="PagerBtnCommand_OnClick" /> <asp:Button ID="Nextpage" runat="server" CommandName="next" Text="下一頁" OnClick="PagerBtnCommand_OnClick" /> <asp:Button ID="Lastpage" runat="server" CommandName="last" Text="尾頁" key="last" OnClick="PagerBtnCommand_OnClick" /> </td> <td> <asp:Label ID="lbjumppage" runat="server" Text="跳轉到第"></asp:Label> <asp:TextBox ID="GotoPage" runat="server" Width="25px"></asp:TextBox> <asp:Label ID="lbye" runat="server" Text="頁"></asp:Label> <asp:Button ID="Jump" runat="server" Text="跳轉" CommandName="jump" OnClick="PagerBtnCommand_OnClick" /> </td> </tr> </table> </div> </div> </div>
布局的效果如下:
二、后台的代碼實現
我會一點一點向大家講解清楚,這個分頁的原理
Members:這里主要定義幾個全局的變量,主要用來記錄信息的數量、頁的數量和當前頁
#region Members const int PAGESIZE = 10;//每頁顯示信息數量 int PagesCount, RecordsCount;//記錄總頁數和信息總條數 int CurrentPage, Pages, JumpPage;//當前頁,信息總頁數(用來控制按鈕失效),跳轉頁碼 const string COUNT_SQL = "select count(*) from p_user"; #endregion
Methods:
1、GetRecordsCount:該方法主要用來獲取當前信息的總數,有一個sqlSearch參數,默認的為default,即初始化頁面時,查詢所有信息的總條數,當用戶輸入要搜索的用戶名進行檢索時,獲取符合用戶檢索條件的信息的總條數
/// <summary> /// 獲取信息總數 /// </summary> /// <param name="sqlSearch"></param> /// <returns></returns> public static int GetRecordsCount(string sqlRecordsCount) { string sqlQuery; if (sqlRecordsCount == "default") { sqlQuery = COUNT_SQL; } else { sqlQuery = sqlRecordsCount; } int RecordCount = 0; SqlCommand cmd = new SqlCommand(sqlQuery, Conn()); RecordCount = Convert.ToInt32(cmd.ExecuteScalar()); cmd.Connection.Close(); return RecordCount; }
2、OverPage:該方法主要用來計算剩余頁,當前設置的為每頁顯示10條數據,如何符合條件的數據有11條,則要顯示2頁
/// <summary> /// 計算余頁 /// </summary> /// <returns></returns> public int OverPage() { int pages = 0; if (RecordsCount % PAGESIZE != 0) pages = 1; else pages = 0; return pages; }
3、ModPage:該方法也是用計算余頁,主要用來防止SQL執行溢出
/// <summary> /// 計算余頁,防止SQL語句執行時溢出查詢范圍 /// </summary> /// <returns></returns> public int ModPage() { int pages = 0; if (RecordsCount % PAGESIZE == 0 && RecordsCount != 0) pages = 1; else pages = 0; return pages; }
4、Conn:該方法用來創建數據連接對象,在使用的時候只需改成自己的數據庫名即可
/// <summary> /// 數據連接對象 /// </summary> /// <returns></returns> public static SqlConnection Conn() { SqlConnection conn = new SqlConnection("data source=.;initial catalog=DB_GSL_ZCW;Integrated Security=true"); conn.Open(); return conn; }
5、GridViewDataBind:該方法主要用來數據綁定,如果傳入的參數為default則,默認的綁定所有的數據,否則,則綁定過濾過的數據
/// <summary> /// GridView數據綁定,根據傳入參數的不同,進行不同方式的查詢, /// </summary> /// <param name="sqlSearch"></param> private void GridViewDataBind(string sqlSearch) { CurrentPage = (int)ViewState["PageIndex"]; //從ViewState中讀取頁碼值保存到CurrentPage變量中進行按鈕失效運算 Pages = (int)ViewState["PagesCount"]; //從ViewState中讀取總頁參數進行按鈕失效運算 //判斷四個按鈕(首頁、上一頁、下一頁、尾頁)狀態 if (CurrentPage + 1 > 1)//當前頁是否為首頁 { Fistpage.Enabled = true; Prevpage.Enabled = true; } else { Fistpage.Enabled = false; Prevpage.Enabled = false; } if (CurrentPage == Pages)//當前頁是否為尾頁 { Nextpage.Enabled = false; Lastpage.Enabled = false; } else { Nextpage.Enabled = true; Lastpage.Enabled = true; } DataSet ds = new DataSet(); string sqlResult; //根據傳入參數sqlSearch進行判斷,如果為default則為默認的分頁查詢,否則為添加了過濾條件的分頁查詢 if (sqlSearch == "default") { sqlResult = "Select Top " + PAGESIZE + "user_serialid,username,displayname,orgcode,orgname from p_user where user_serialid not in(select top " + PAGESIZE * CurrentPage + " user_serialid from p_user order by user_serialid asc) order by user_serialid asc"; } else { sqlResult = sqlSearch; } SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlResult, Conn()); sqlAdapter.Fill(ds, "Result"); UserGridView.DataSource = ds.Tables["Result"].DefaultView; UserGridView.DataBind(); //顯示Label控件lbCurrentPaget和文本框控件GotoPage狀態 lbCurrentPage.Text = (CurrentPage + 1).ToString(); GotoPage.Text = (CurrentPage + 1).ToString(); sqlAdapter.Dispose(); }
6、Page_Load:頁面加載函數,主要是在首次進入頁面時,進行初始化,默認的獲取所有的信息
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack)//首次進行該頁時,頁面初始化 { RecordsCount = GetRecordsCount("default");//默認信息總數 PagesCount = RecordsCount / PAGESIZE + OverPage();//默認的頁總數 ViewState["PagesCount"] = RecordsCount / PAGESIZE - ModPage();//保存末頁索引,比頁總數小1 ViewState["PageIndex"] = 0;//保存頁面初始索引從0開始 ViewState["JumpPages"] = PagesCount; //保存頁總數,跳頁時判斷用戶輸入數是否超出頁碼范圍 //顯示lbPageCount、lbRecordCount的狀態 lbPageCount.Text = PagesCount.ToString(); lbRecordCount.Text = RecordsCount.ToString(); //判斷跳頁文本框失效 if (RecordsCount <= 10) { GotoPage.Enabled = false; } GridViewDataBind("default");//調用數據綁定函數TDataBind()進行數據綁定運算 } }
7、PagerBtnCommand_OnClick:該方法主要用來處理設計視圖頁的“首頁”、“下一頁”,“上一頁”,“尾頁”,“查詢”按鈕的Click事件,主要通過不同按鈕的CommandName屬性來分別處理,需要在前台為每一個按鈕相應的CommandName屬性賦值,如果用戶點擊的是“查詢”按鈕,這個時候需要對查詢的Sql語句進行重寫,加入過濾條件,即用戶輸入的查詢的條件
/// <summary> /// 頁面按鈕Click處理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void PagerBtnCommand_OnClick(object sender, EventArgs e) { CurrentPage = (int)ViewState["PageIndex"]; //從ViewState中讀取頁碼值保存到CurrentPage變量中進行參數運算 Pages = (int)ViewState["PagesCount"];//從ViewState中讀取總頁參數運算 Button btn = sender as Button; string sqlResult="default"; if (btn != null) { string cmd = btn.CommandName; switch (cmd)//根據不同的CommandName做出不同的處理 { case "next": CurrentPage++; break; case "prev": CurrentPage--; break; case "last": CurrentPage = Pages; break; case "search": if (!string.IsNullOrEmpty(SearchName.Text)) { RecordsCount = GetRecordsCount("select count(*) from p_user where username like '" + SearchName.Text + "%'");//獲取過濾后的總記錄數 PagesCount = RecordsCount / PAGESIZE + OverPage();//該變量為頁總數 ViewState["PagesCount"] = RecordsCount / PAGESIZE - ModPage();//該變量為末頁索引,比頁總數小1 ViewState["PageIndex"] = 0;//保存一個為0的頁面索引值到ViewState,頁面索引從0開始 ViewState["JumpPages"] = PagesCount; //保存PageCount到ViewState,跳頁時判斷用戶輸入數是否超出頁碼范圍 //顯示lbPageCount、lbRecordCount的狀態 lbPageCount.Text = PagesCount.ToString(); lbRecordCount.Text = RecordsCount.ToString(); //判斷跳頁文本框失效 if (RecordsCount <= 10) GotoPage.Enabled = false; sqlResult = "Select Top " + PAGESIZE + "user_serialid,username,displayname,orgcode,orgname from p_user where user_serialid not in(select top " + PAGESIZE * CurrentPage + " user_serialid from p_user order by user_serialid asc) and username like '" + SearchName.Text + "%' order by user_serialid asc"; } else { Response.Write("請輸入您所要查找的用戶姓名!"); } break; case "jump": JumpPage = (int)ViewState["JumpPages"]; //從ViewState中讀取可用頁數值保存到JumpPage變量中 //判斷用戶輸入值是否超過可用頁數范圍值 if(Int32.Parse(GotoPage.Text) > JumpPage || Int32.Parse(GotoPage.Text) <= 0) Response.Write("<script>alert('頁碼范圍越界!')</script>"); else { int InputPage = Int32.Parse(GotoPage.Text.ToString()) - 1; //轉換用戶輸入值保存在int型InputPage變量中 ViewState["PageIndex"] = InputPage; CurrentPage = InputPage; //寫入InputPage值到ViewState["PageIndex"]中 sqlResult = "Select Top " + PAGESIZE + "user_serialid,username,displayname,orgcode,orgname from p_user where user_serialid not in(select top " + PAGESIZE * CurrentPage + " user_serialid from p_user order by user_serialid asc) and username like '" + SearchName.Text + "%' order by user_serialid asc"; } break; default: CurrentPage = 0; break; } ViewState["PageIndex"] = CurrentPage; //將運算后的CurrentPage變量再次保存至ViewState GridViewDataBind(sqlResult);//調用數據綁定函數TDataBind() } }
8、btn_Reset_Click:該方法主要用來進行重置,用戶完成一次查詢之后,需要重置,才能進行下一次的查詢操作
protected void btnReset_Click(object sender, EventArgs e) ( RecordsCount = GetRecordsCount("default");//默認信息總數 PagesCount = RecordsCount / PAGESIZE + OverPage();//默認的頁總數 ViewState["PagesCount"] = RecordsCount / PAGESIZE - ModPage();//保存末頁索引,比頁總數小1 ViewState["PageIndex"] = 0;//保存頁面初始索引從0開始 ViewState["JumpPages"] = PagesCount; //保存頁總數,跳頁時判斷用戶輸入數是否超出頁碼范圍 //顯示lbPageCount、lbRecordCount的狀態 lbPageCount.Text = PagesCount.ToString(); lbRecordCount.Text = RecordsCount.ToString(); //判斷跳頁文本框失效 if (RecordsCount <= 10) { GotoPage.Enabled = false; } GridViewDataBind("default");//調用數據綁定函數TDataBind()進行數據綁定運算 }
這里的高效分頁方法主要用的是select top 10 Id ,Name from tb where Id not in (select top 10*N from tb order by Id asc) order by Id asc
示例中的N代表的是頁數,之前原子里也有很多關於高效分頁的討論,這里就不再多說了,我個人覺得這個分頁語句效果還不錯,當然除此之外還有row_number()函數分頁、select Max() 分頁等等方法,之前也有總結過,有興趣的朋友可以看一下我之前寫的ListView和Repeater高效分頁這篇文章,里邊講述的也很詳細,只要你一步一步的照着去操練應該問題不大的。
這里需要解釋一下的是為什么沒有有數據綁定控件直接進行綁定,因為在sharepoint2010項目里邊它支持的數據源控件只有XMLDataSource,所以就只有自己動手實現了。
好了今天就到這里了,希望能給大家帶來些幫助吧!還請多多指教!