首页 > 开发 > 综合 > 正文

改善DataGrid的默認分頁使其更友好

2024-07-21 02:22:45
字体:
来源:转载
供稿:网友

最大的网站源码资源下载站,

改善datagrid的默認分頁使其更友好

        datagrid是.net平台下開發web應用程序最常用的控件,使用該控件可以幫助您專注與商務邏輯的開發,數據的顯示交給它來處理就好了,隻要簡單的設置一些相關的屬性,一張漂亮的表格就出來了,同時,它提供的模板列更大的提高了它的可編程性,使我們的設計更加靈活,想想都覺得這是一件興奮的事!然而,令人感覺美中不足的是,它的分頁功能實在是不怎麼樣,光禿禿的幾個數字掛在上面,既沒有統計信息又沒有跳頁功能,我想,這樣的用戶體驗太乏味了一點吧!於是我就想能不能改善它的分頁功能呢,使它具備上述功能!恩,現在想法有了,問題剩下如何實現?先讓我們想一下,datagrid最終在客戶端表現為一個table,也就是說服務器將datagrid解析為一段以<table>開始</table>結束的html代碼,然後將這段代碼發送到請求頁面的客戶端,請注意這個過程是先解析然後發送,既然過程是這樣的,那問題也就迎刃而解了,我們可以在解析後發送前這段時間為控件增加新的功能啊!接下來的問題是我要如何攔截到這段時間並讓整個過程停住去執行我寫的代碼,別急,先讓我們了解一下datagrid的組成結構,datagrid由行集和列集構成,它們分別在服務端表現為datagrid.items和datagrid.columns,datagrid分頁區是一個datagriditem,包含在整個items集合中,每當datagrid在創建一個item時,都會引發一個itemcreated事件,我們可以通過捕捉該事件來獲取"datagrid分頁區"對象,並在該對象呈現至它包含的page對象時,也就是發生prerender事件時,編寫代碼為其加入新功能,如下所示:

private void dgproducts_itemcreated(object sender, system.web.ui.webcontrols.datagriditemeventargs e)

{

     if (e.item.itemtype == listitemtype.pager)

     {

           // 獲取datagrid分頁區對象並為其指定prerender事件的處理函數

           pageritem = e.item;

           pageritem.prerender += new system.eventhandler(this.pageritem_prerender);

     }

}

private void pageritem_prerender(object sender, eventargs e)

{

     // 編寫事件處理代碼實現頁面統計信息以及跳頁功能

     .......

} 由於在執行上述事件時datagrid已經經過解析生成了html,所以我們也隻能向其中添加html代碼來實現所需的功能。最終生成的新的分頁如下圖所示:

在實現跳頁功能時我使用javascript將用戶在文本框中輸入的值保存在一個html隱藏字段裡,然後在服務端獲取該隱藏字段的值,並將datagrid指定到該頁,我曾經試過用url傳參數的方式並指定window.location為新的url字符串,可是使用window.location會導致page_load()執行兩次。從而得不到想要的結果。我也考慮過使用viewstate,可那個文本框和按鈕是動態添加進去的html標簽,事先沒有在服務端定義,又如何操控它們呢!於是這個念頭也就一閃而過了!到最後也隻有採用"隱藏字段"這種不怎麼高級但確實能解決的方法。以下是點"go"按鈕時執行的javascript函數:

function go(ctrl,max)

{

     // 驗証用戶輸入值是否符合要求

     if(ctrl.value >= 1 && ctrl.value <= max.innertext)

     {

           // 將輸入值保存到隱藏字段裡

           document.all.pagenum.value = ctrl.value;

     }

     else

     {

           alert('您輸入的頁碼必須是符合頁面要求的數字,最大值是:'+max.innertext);

           ctrl.value="";

           ctrl.focus();

           return false;

     }

}

全部代碼如下:

.apsx.cs

using system;

using system.collections;

using system.componentmodel;

using system.data;

using system.data.sqlclient;

using system.drawing;

using system.web;

using system.web.sessionstate;

using system.web.ui;

using system.web.ui.webcontrols;

using system.web.ui.htmlcontrols;

 

namespace sky_msdndatagrid

{

     /// <summary>

     /// sortdatagrid 的摘要描述。

     /// </summary>

     public class sortdatagrid : system.web.ui.page

     {

           protected system.web.ui.webcontrols.datagrid dgproducts;

           private string connstr;

           private string cmdtext;

           private datagriditem pageritem;

           protected system.web.ui.htmlcontrols.htmlinputhidden pagenum;

           private int pagernum = 1;

           private datatable producttable;

    

           private void page_load(object sender, system.eventargs e)

           {

                // 頁面加載時判斷隱藏字段中是否有值,如果有值代表用戶使用了跳頁功能,並將datagrid的當前頁設為用戶指定頁

                if (this.pagenum.value != string.empty)

                {

                     this.dgproducts.currentpageindex =  convert.toint32(this.pagenum.value) - 1;

                     if (viewstate["sortexprname"] != null)

                           this.binddata("select * from products order by " + viewstate["sortexprname"].tostring() + " asc");

                     else

                           this.binddata("select * from products");

                     this.pagenum.value = string.empty;

                }

                else

                {

                     this.binddata("select * from products");

                }

           }

          

           // 綁定數據

           private void binddata(string sqltext)

           {

                this.connstr = "server=localhost;database=northwind;uid=sa";

                this.cmdtext = sqltext;

 

                sqlconnection conn = new sqlconnection();

                sqlcommand cmd = new sqlcommand();

                sqldataadapter adapter = new sqldataadapter();

                producttable = new datatable("products");

 

                conn.connectionstring = this.connstr;

                cmd.commandtype = commandtype.text;

                cmd.commandtext = this.cmdtext;

                cmd.connection = conn;

                adapter.selectcommand = cmd;

 

                adapter.fill(producttable);

 

                this.dgproducts.datasource = producttable;

                this.dgproducts.databind();

           }

 

           #region web form 設計工具產生的程式碼

           override protected void oninit(eventargs e)

           {

                //

                // codegen: 此為 asp.net web form 設計工具所需的呼叫。

                //

                initializecomponent();

                base.oninit(e);

           }

          

           /// <summary>

           /// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改

           /// 這個方法的內容。

           /// </summary>

           private void initializecomponent()

           {   

                this.dgproducts.itemcreated += new system.web.ui.webcontrols.datagriditemeventhandler(this.dgproducts_itemcreated);

                this.dgproducts.pageindexchanged += new system.web.ui.webcontrols.datagridpagechangedeventhandler(this.dgproducts_pageindexchanged);

                this.dgproducts.sortcommand += new system.web.ui.webcontrols.datagridsortcommandeventhandler(this.dgproducts_sortcommand);

                this.load += new system.eventhandler(this.page_load);

 

           }

           #endregion

          

           // 實現排序功能

           private void dgproducts_sortcommand(object source, system.web.ui.webcontrols.datagridsortcommandeventargs e)

           {

               

                this.dgproducts.currentpageindex = 0;

                viewstate["sortexprname"] = e.sortexpression;

                this.binddata("select * from products order by "+ e.sortexpression + " asc");

           }

 

           private void dgproducts_pageindexchanged(object source, system.web.ui.webcontrols.datagridpagechangedeventargs e)

           {

                this.dgproducts.currentpageindex = e.newpageindex;

                if (viewstate["sortexprname"] != null)

                     this.binddata("select * from products order by " + viewstate["sortexprname"].tostring() + " asc");

                else

                     this.binddata("select * from products");

           }

 

           private void dgproducts_itemcreated(object sender, system.web.ui.webcontrols.datagriditemeventargs e)

           {

                if (e.item.itemtype == listitemtype.pager)

                {

                     // 獲取datagrid分頁區對象並為其指定prerender事件的處理函數

                     pageritem = e.item;

                     pageritem.prerender += new system.eventhandler(this.pageritem_prerender);

                }

           }

 

           private void pageritem_prerender(object sender, eventargs e)

           {

                if (this.pagernum == 1)

                {

                     this.pagernum = this.pagernum - 1;

                     return;

                }

               

                // currentpagenum-當前頁碼 recordcount-總記錄條數 pagecount-頁數

                string currentpagenum = convert.tostring(this.dgproducts.currentpageindex + 1);

                string recordcount = this.producttable.rows.count.tostring();

                string pagecount = this.dgproducts.pagecount.tostring();

               

                // 創建單元格包含頁面統計信息

                tablecell groupcell = new tablecell();

                groupcell.text = "<b><font face='標楷體' size=3><font color=olivedrab>當前第</font><font color=red>" + currentpagenum + "</font><font color=olivedrab>頁 每頁<font color=red>" + this.dgproducts.pagesize.tostring() + "</font>條 (" +

                     "共</font><font color=red>" + recordcount + "</font><font color=olivedrab>條,共</font><font color=red><label id='maxpage'>" + pagecount + "</label></font><font color=olivedrab>頁)</font></font></b>";

               

                // 創建單元格包含跳頁功能

                tablecell opercell = new tablecell();

                opercell.text = "<input type='text' id='textbox' name='t1' size='4' style='border-style: solid; border-width: 1px; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px'>&nbsp" +

                    "<input type='submit' value='go' name='b1' onclick='return go(textbox,maxpage)' style='border-style: solid; border-width: 1px; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px'>";

               

                // pageritem.cells[0]代表datagrid默認分頁,將其所跨列設為1

                pageritem.cells[0].columnspan = 1;

                groupcell.horizontalalign = horizontalalign.left;

                groupcell.columnspan = this.dgproducts.columns.count - 2;

                opercell.horizontalalign = horizontalalign.right;

                pageritem.cells.addat(0,groupcell);

                pageritem.cells.addat(2,opercell);

           }

     }

}

.aspx

<%@ page language="c#" codebehind="sortdatagrid.aspx.cs" autoeventwireup="false" inherits="sky_msdndatagrid.sortdatagrid" %>

<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >

<html>

     <head>

           <title>sortdatagrid</title>

           <meta content="microsoft visual studio .net 7.1" name="generator">

           <meta content="c#" name="code_language">

           <meta content="javascript" name="vs_defaultclientscript">

           <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetschema">

           <script language="javascript">

                function go(ctrl,max)

                {

                     // 驗証用戶輸入值是否符合要求

                     if(ctrl.value >= 1 && ctrl.value <= max.innertext)

                     {

                           // 將輸入值保存到隱藏字段裡

                           document.all.pagenum.value = ctrl.value;

                     }

                     else

                     {

                     alert('您輸入的頁碼必須是符合頁面要求的數字,最大值是:'+max.innertext);

                     ctrl.value="";

                     ctrl.focus();

                          return false;

                     }

                }

           </script>

     </head>

     <body ms_positioning="gridlayout">

           <form id="form1" method="post" runat="server">

                <asp:datagrid id="dgproducts" runat="server" width="100%" allowsorting="true" autogeneratecolumns="false" allowpaging="true">

                     <footerstyle forecolor="#4a3c8c" backcolor="#b5c7de"></footerstyle>

                     <selecteditemstyle font-bold="true" forecolor="#f7f7f7" backcolor="#738a9c"></selecteditemstyle>

                     <alternatingitemstyle font-size="x-small" backcolor="#ccffff"></alternatingitemstyle>

                     <itemstyle font-size="x-small" backcolor="white"></itemstyle>

                     <headerstyle font-size="x-small" font-bold="true" horizontalalign="center" forecolor="white" backcolor="#99cccc"></headerstyle>

                     <columns>

                           <asp:boundcolumn datafield="productid" headertext="產品編號">

                                <headerstyle width="15%"></headerstyle>

                                <itemstyle horizontalalign="center"></itemstyle>

                           </asp:boundcolumn>

                           <asp:boundcolumn datafield="supplierid" headertext="供應商編號">

                                <headerstyle width="15%"></headerstyle>

                                <itemstyle horizontalalign="center"></itemstyle>

                           </asp:boundcolumn>

                           <asp:boundcolumn datafield="productname" sortexpression="productname" headertext="產品名稱">

                                <headerstyle horizontalalign="left" width="30%"></headerstyle>

                           </asp:boundcolumn>

                           <asp:boundcolumn datafield="unitprice" sortexpression="unitprice" headertext="產品單價">

                                <headerstyle width="20%"></headerstyle>

                                <itemstyle horizontalalign="center"></itemstyle>

                           </asp:boundcolumn>

                           <asp:boundcolumn datafield="unitsinstock" sortexpression="unitsinstock" headertext="供應單價">

                                <headerstyle width="20%"></headerstyle>

                                <itemstyle horizontalalign="center"></itemstyle>

                           </asp:boundcolumn>

                     </columns>

                     <pagerstyle font-size="x-small" horizontalalign="center" forecolor="#4a3c8c" backcolor="lightblue" mode="numericpages"></pagerstyle>

                </asp:datagrid>

                <input id="pagenum" runat="server" type="hidden">

           </form>

     </body>

</html>

最終運行效果:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表