ASP. net2.0 gridview multi-column sorting, display the sorting icon, pagination

Source: Internet
Author: User

Recently, when using the Asp.net 2.0 gridview control, we found that the sorting and paging functions Microsoft implemented are very simple. For example, sorting triggers the PostBack of the entire page when clicking the column name, and then sorting, however, there is no icon in the column that shows ascending and descending order, which will confuse the end user's use, because I do not know whether it is ascending or descending, so the first problem solved today is to display the icon in the column in ascending and descending order. The second problem to be solved is that by default, the gridview can only be sorted by column, that is to say, you cannot sort multiple columns. In actual applications, sorting by only one column cannot meet the business requirements. The third is the pagination problem of the gridview, where the pre-defined page number of the gridview is displayed, in practice, pagination may not be as simple as displaying only the home page, Previous Page, next page, last page, or number pages. You need to jump to the current page, the total number of pages and more detailed information.

1. display of multiple column sorting and sorting icons in the gridview

First, we can create a new class library.ProgramTo reference the system. Web. dll file.
Create a new class that inherits from the gridview control. You only need to repeat some methods.
In my demo, we used single-column sorting. If multi-column sorting is enabled, set the control's allowmulticolumnsorting to true.
Sort multiple columns.

1 public class webgridview: gridview
2 {
3 attribute # region attribute
4/** // <summary>
5 // whether to enable or disable multi-column sorting
6 /// </Summary>
7 [
8 description ("whether to enable multi-column sorting "),
9 category ("sort "),
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 // icon displayed in ascending order
27 /// </Summary>
28 [
29 description ("icon displayed in ascending order "),
30 category ("sort "),
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 // icon displayed in descending order
49 // </Summary>
50 [
51 description ("show icons in descending order "),
52 category ("sort "),
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 rewrite method # region rewrite Method
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 protected methods # region protected Methods
93/*** // <summary>
94 // obtain the sort expression
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 // modify the sorting order
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 // obtain the current expression to sort the selected columns
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 // draw an image in ascending and descending order
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}

Second, detailed page information is displayed. This function is not encapsulated in the form of controls. You can directly operate on the last page in the gridview_databound event.
Below are the multi-column sorting and paging displayCodeDemo

<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 = "Current page:" + currentpage. tostring () +
"/" + Customersgridview. pagecount. tostring ();
}
}
</SCRIPT>
<HTML>
<Body>
<Form ID = "form1" runat = "server">
<H3>
Gridview pagertemplate example <Asp: webgridview id = "customersgridview" ceceid = "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>
& Lt; table width = "100%" & gt;
<Tr>
& Lt; TD width = "70%" & gt;
<Asp: Label id = "messagelabel" forecolor = "blue" text = "page number:" runat = "server"/>
<Asp: dropdownlist id = "pagedropdownlist" autopostback = "true" onselectedindexchanged = "pagedropdownlist_selectedindexchanged"
Runat = "server"/>
<Asp: linkbutton commandname = "page" commandargument = "first" id = "linkbtnfirst" runat = "server"> homepage </ASP: linkbutton>
<Asp: linkbutton commandname = "page" commandargument = "Prev" id = "linkbtnprev" runat = "server"> previous page </ASP: linkbutton>
<Asp: linkbutton commandname = "page" commandargument = "Next" id = "linkbtnnext" runat = "server"> next page </ASP: linkbutton>
<Asp: linkbutton commandname = "page" commandargument = "last" id = "linkbtnlast" runat = "server"> last page </ASP: linkbutton>
</TD>
& Lt; TD width = "70%" align = "right" & gt;
<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 [MERs]"
Connectionstring = "<% $ connectionstrings: northwindconnectionstring %>" runat = "server">
</ASP: sqldatasource>
</Form>
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.