欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.Net2.0 GridView 多列排序,显示排序图标,分页

程序员文章站 2023-11-27 22:03:46
    最近在使用asp.net 2.0的gridview 控件时,发现排序与分页功能microsoft实现的都很简单,比如排序,在点击列名的...

    最近在使用asp.net 2.0的gridview 控件时,发现排序与分页功能microsoft实现的都很简单,比如排序,在点击列名的时候来触发整页的postback,然后排序,但是在列头上没有一个显示升序降序的图标,这会让最终用户使用时很迷惑,因为不知道是升序了还是降序了,所以今天首先解决的第一问题就是升序降序在列上显示图标,第二要解决的问题是默认gridview按列排序只能排一列的,也就是不能进行多列排序,而在实际应用中仅仅按照一列来排序是不能满足业务需求的,第三是gridview 分页问题,gridview预定义的分页页码显示,比较简单,而实际应用中,分页可能不是只显示首页,上一页,下一页,末页,或者是数字的页码那么简单,应该更需要,跳转,当前的页码,总页数等,更详尽的信息。

第一:gridview 多列排序与排序图标显示

首先我们可以新建一个类库程序,主要需要引用system.web.dll文件
然后新建一个类,这个类继承与gridview控件,我们只需要对部分方法进行重新即可。
我的演示的例子,采用了单列排序,如果启用多列排序,把控件的allowmulticolumnsorting设置为true就是
多列排序。

  1    public class webgridview:gridview
  2    {
  3        属性#region 属性
  4        /**//// <summary>
  5        /// 是否启用或者禁止多列排序
  6        /// </summary>
  7        [
  8        description("是否启用多列排序功能"),
  9        category("排序"),
 10        defaultvalue("false"),
 11        ]
 12        public bool allowmulticolumnsorting
 13        {
 14            get
 15            {
 16                object o = viewstate["enablemulticolumnsorting"];
 17                return (o != null ? (bool)o : false);
 18            }
 19            set
 20            {
 21                allowsorting = true;
 22                viewstate["enablemulticolumnsorting"] = value;
 23            }
 24        }
 25        /**//// <summary>
 26        /// 升序时显示图标
 27        /// </summary>
 28        [
 29        description("升序时显示图标"),
 30        category("排序"),
 31        editor("system.web.ui.design.urleditor", typeof(system.drawing.design.uitypeeditor)),
 32        defaultvalue(""),
 33
 34        ]
 35        public string sortascimageurl
 36        {
 37            get
 38            {
 39                object o = viewstate["sortimageasc"];
 40                return (o != null ? o.tostring() : "");
 41            }
 42            set
 43            {
 44                viewstate["sortimageasc"] = value;
 45            }
 46        }
 47        /**//// <summary>
 48        /// 降序时显示图标
 49        /// </summary>
 50        [
 51        description("降序时显示图标"),
 52        category("排序"),
 53        editor("system.web.ui.design.urleditor", typeof(system.drawing.design.uitypeeditor)),
 54        defaultvalue(""),
 55        ]
 56        public string sortdescimageurl
 57        {
 58            get
 59            {
 60                object o = viewstate["sortimagedesc"];
 61                return (o != null ? o.tostring() : "");
 62            }
 63            set
 64            {
 65                viewstate["sortimagedesc"] = value;
 66            }
 67        }
 68        #endregion
 69        重写方法#region 重写方法
 70        protected override void onsorting(gridviewsorteventargs e)
 71        {
 72            if (allowmulticolumnsorting)
 73            {
 74                e.sortexpression = getsortexpression(e);
 75            }
 76
 77            base.onsorting(e);
 78        }
 79        protected override void onrowcreated(gridviewroweventargs e)
 80        {
 81            if (e.row.rowtype == datacontrolrowtype.header)
 82            {
 83                if (sortexpression != string.empty)
 84                {
 85                    displaysortorderimages(sortexpression, e.row);
 86                    this.createrow(0, 0, datacontrolrowtype.emptydatarow, datacontrolrowstate.normal);
 87                }
 88            }
 89            base.onrowcreated(e);
 90        }
 91        #endregion
 92        受保护的方法#region 受保护的方法
 93        /**//// <summary>
 94        ///  获取排序表达式
 95        /// </summary>
 96        protected string getsortexpression(gridviewsorteventargs e)
 97        {
 98            string[] sortcolumns = null;
 99            string sortattribute = sortexpression;
100
101            if (sortattribute != string.empty)
102            {
103                sortcolumns = sortattribute.split(",".tochararray());
104            }
105            if (sortattribute.indexof(e.sortexpression) > 0 || sortattribute.startswith(e.sortexpression))
106            {
107                sortattribute = modifysortexpression(sortcolumns, e.sortexpression);
108            }
109            else
110            {
111                sortattribute += string.concat(",", e.sortexpression, " asc ");
112            }
113            return sortattribute.trimstart(",".tochararray()).trimend(",".tochararray());
114
115        }
116        /**//// <summary>
117        ///  修改排序顺序
118        /// </summary>
119        protected string modifysortexpression(string[] sortcolumns, string sortexpression)
120        {
121            string ascsortexpression = string.concat(sortexpression, " asc ");
122            string descsortexpression = string.concat(sortexpression, " desc ");
123
124            for (int i = 0; i < sortcolumns.length; i++)
125            {
126
127                if (ascsortexpression.equals(sortcolumns[i]))
128                {
129                    sortcolumns[i] = descsortexpression;
130                }
131
132                else if (descsortexpression.equals(sortcolumns[i]))
133                {
134                    array.clear(sortcolumns, i, 1);
135                }
136            }
137
138            return string.join(",", sortcolumns).replace(",,", ",").trimstart(",".tochararray());
139
140        }
141        /**//// <summary>
142        ///  获取当前的表达式对所选列进行排序
143        /// </summary>
144        protected void searchsortexpression(string[] sortcolumns, string sortcolumn, out string sortorder, out int sortorderno)
145        {
146            sortorder = "";
147            sortorderno = -1;
148            for (int i = 0; i < sortcolumns.length; i++)
149            {
150                if (sortcolumns[i].startswith(sortcolumn))
151                {
152                    sortorderno = i + 1;
153                    if (allowmulticolumnsorting)
154                    {
155                        sortorder = sortcolumns[i].substring(sortcolumn.length).trim();
156                    }
157                    else
158                    {
159                        sortorder = ((sortdirection == sortdirection.ascending) ? "asc" : "desc");
160                    }
161                }
162            }
163        }
164        /**//// <summary>
165        ///  绘制升序降序的图片
166        /// </summary>
167        protected void displaysortorderimages(string sortexpression, gridviewrow dgitem)
168        {
169            string[] sortcolumns = sortexpression.split(",".tochararray());
170
171            for (int i = 0; i < dgitem.cells.count; i++)
172            {
173                if (dgitem.cells[i].controls.count > 0 && dgitem.cells[i].controls[0] is linkbutton)
174                {
175                    string sortorder;
176                    int sortorderno;
177                    string column = ((linkbutton)dgitem.cells[i].controls[0]).commandargument;
178                    searchsortexpression(sortcolumns, column, out sortorder, out sortorderno);
179                    if (sortorderno > 0)
180                    {
181                        string sortimgloc = (sortorder.equals("asc") ? sortascimageurl : sortdescimageurl);
182
183                        if (sortimgloc != string.empty)
184                        {
185                            image imgsortdirection = new image();
186                            imgsortdirection.imageurl = sortimgloc;
187                            dgitem.cells[i].controls.add(imgsortdirection);
188
189                        }
190                        else
191                        {
192
193                            if (allowmulticolumnsorting)
194                            {
195                                literal litsortseq = new literal();
196                                litsortseq.text = sortorderno.tostring();
197                                dgitem.cells[i].controls.add(litsortseq);
198
199                            }
200                        }
201                    }
202                }
203            }
204
205        }
206        #endregion
207    }

第二:详尽的分页信息显示,此功能没有封装成控件形式,直接在gridview_databound事件中对尾页操作即可。
下面是多列排序与分页显示代码的演示

<script runat="server">
    void pagedropdownlist_selectedindexchanged(object sender, eventargs e)
    {
        gridviewrow pagerrow = customersgridview.bottompagerrow;
        dropdownlist pagelist = (dropdownlist)pagerrow.cells[0].findcontrol("pagedropdownlist");
        customersgridview.pageindex = pagelist.selectedindex;
    }
    void customersgridview_databound(object sender, eventargs e)
    {
        gridviewrow pagerrow = customersgridview.bottompagerrow;
        linkbutton linkbtnfirst = (linkbutton)pagerrow.cells[0].findcontrol("linkbtnfirst");
        linkbutton linkbtnprev = (linkbutton)pagerrow.cells[0].findcontrol("linkbtnprev");
        linkbutton linkbtnnext = (linkbutton)pagerrow.cells[0].findcontrol("linkbtnnext");
        linkbutton linkbtnlast = (linkbutton)pagerrow.cells[0].findcontrol("linkbtnlast");
        if (customersgridview.pageindex == 0)
        {
            linkbtnfirst.enabled = false;
            linkbtnprev.enabled = false;
        }
        else if (customersgridview.pageindex == customersgridview.pagecount-1)
        {
            linkbtnlast.enabled  = false;
            linkbtnnext.enabled = false;
        }
        else if (customersgridview.pagecount<=0)
        {
            linkbtnfirst.enabled = false;
            linkbtnprev.enabled = false;
            linkbtnnext.enabled = false;
            linkbtnlast.enabled = false;
        }
        dropdownlist pagelist = (dropdownlist)pagerrow.cells[0].findcontrol("pagedropdownlist");
        label pagelabel = (label)pagerrow.cells[0].findcontrol("currentpagelabel");
        if (pagelist != null)
        {
            for (int i = 0; i < customersgridview.pagecount; i++)
            {
                int pagenumber = i + 1;
                listitem item = new listitem(pagenumber.tostring() + "/" + customersgridview.pagecount.tostring(), pagenumber.tostring());
                if (i == customersgridview.pageindex)
                {
                    item.selected = true;
                }
                pagelist.items.add(item);
            }
        }
        if (pagelabel != null)
        {
            int currentpage = customersgridview.pageindex + 1;
            pagelabel.text = "当前页: " + currentpage.tostring() +
              " / " + customersgridview.pagecount.tostring();
        }
    }
</script>
<html>
<body>
    <form id="form1" runat="server">
        <h3>
            gridview pagertemplate example</h3>
        <asp:webgridview id="customersgridview" datasourceid="customerssqldatasource" autogeneratecolumns="true"
            allowpaging="true" ondatabound="customersgridview_databound" sortascimageurl="~\images\arrow-up.gif" sortdescimageurl="~\images\arrow-down.gif" runat="server" allowsorting="true" width="723px">
            <pagerstyle forecolor="blue" backcolor="lightblue" />
            <pagertemplate>
                <table width="100%">
                    <tr>
                        <td width="70%">
                            <asp:label id="messagelabel" forecolor="blue" text="页码:" runat="server" />
                            <asp:dropdownlist id="pagedropdownlist" autopostback="true" onselectedindexchanged="pagedropdownlist_selectedindexchanged"
                                runat="server" />
                            <asp:linkbutton commandname="page" commandargument="first" id="linkbtnfirst" runat="server">首页</asp:linkbutton>
                            <asp:linkbutton commandname="page" commandargument="prev" id="linkbtnprev" runat="server">上一页</asp:linkbutton>
                            <asp:linkbutton commandname="page" commandargument="next" id="linkbtnnext" runat="server">下一页</asp:linkbutton>
                            <asp:linkbutton commandname="page" commandargument="last" id="linkbtnlast" runat="server">末页</asp:linkbutton>
                        </td>
                        <td width="70%" align="right">
                            <asp:label id="currentpagelabel" forecolor="blue" runat="server" />
                        </td>
                    </tr>
                </table>
            </pagertemplate>
       </asp:webgridview>
        <asp:sqldatasource id="customerssqldatasource" selectcommand="select [customerid], [companyname], [address], [city], [postalcode], [country] from [customers]"
            connectionstring="<%$ connectionstrings:northwindconnectionstring%>" runat="server">
        </asp:sqldatasource>
    </form>
</body>
</html>