简单地扩展GridView控件的功能。扩展的功能有:当前页/共几页,首页 上一页 下一页 末页 go[]ok
而且还能把gridview导入到excel中。
Code
1namespaceKFC
2{
3usingSystem;
ponentModel;
5usingSystem.Drawing.Design;
6usingSystem.IO;
7usingSystem.Runtime.InteropServices;
8usingSystem.Web;
9usingSystem.Web.UI;
10usingSystem.Web.UI.HtmlControls;
11usingSystem.Web.UI.WebControls;
12
13publicclassmyGridView:GridView
14{
15protectedvoidbtnExport_Click(objectsender,ImageClickEventArgse)
16{
17ImageButtonbutton=(ImageButton)sender;
18GridViewparent=(GridView)button.Parent.Parent.Parent.Parent;
19HttpResponseresponse=this.Context.ApplicationInstance.Response;
20if((parent.Rows.Count+1)<0x10000)
21{
22parent.AllowPaging=false;
23parent.DataBind();
24StringWriterwriter=newStringWriter();
25HtmlTextWriterwriter2=newHtmlTextWriter(writer);
26HtmlFormchild=newHtmlForm();
27response.Charset="gb2312";
28response.ContentEncoding=System.Text.Encoding.UTF8;
29response.ContentType="application/vnd.ms-word";
30response.AddHeader("content-disposition","attachment;filename=Report.doc");
31
32
33this.EnableViewState=false;
34this.Page.Controls.Add(child);
35child.Controls.Add(parent);
36this.ClearControls(parent);
37child.RenderControl(writer2);
38response.Write(writer.ToString());
39response.End();
40parent.AllowPaging=true;
41parent.DataBind();
42}
43else
44{
45response.Write("记录数量过大,无法导出到Excel。");
46}
47}
48
49protectedvoidButton1_Click(objectsender,EventArgse)
50{
51Buttonbutton=(Button)sender;
52myGridViewparent=(myGridView)button.Parent.Parent.Parent.Parent;
53HttpResponseresponse=this.Context.ApplicationInstance.Response;
54response.Clear();
55response.AddHeader("content-disposition","attachment;filename=FileName.xls");
56response.Charset="gb2312";
57response.ContentType="application/vnd.xls";
58StringWriterwriter=newStringWriter();
59HtmlTextWriterwriter2=newHtmlTextWriter(writer);
60parent.AllowPaging=false;
61parent.DataBind();
62parent.RenderControl(writer2);
63response.Write(writer.ToString());
64response.End();
65parent.AllowPaging=true;
66parent.DataBind();
67}
68
69privatevoidClearControls(Controlcontrol)
70{
71for(inti=control.Controls.Count-1;i>=0;i--)
72{
73this.ClearControls(control.Controls[i]);
74}
75if((controlisImageButton)||(controlisImage))
76{
77control.Parent.Controls.Remove(control);
78}
79if(controlisTableCell)
80{
81for(intj=0;j<control.Controls.Count;j++)
82{
83LiteralControlcontrol2;
84if((control.Controls[j]isImageButton)||(control.Controls[j]isImage))
85{
86control.Controls.Remove(control.Controls[j]);
87}
88if(control.Controls[j]isCheckBox)
89{
90CheckBoxbox=(CheckBox)control.Controls[j];
91control2=newLiteralControl();
92control2.Text=box.Checked?"true":"false";
93control.Controls.Add(control2);
94control.Controls.Remove(box);
95}
96elseif(!(control.Controls[j]isLabel)&&!(control.Controls[j]isLiteralControl))
97{
98Controlcontrol3=control.Controls[j];
99if(control3.GetType().GetProperty("SelectedItem")!=null)
100{
101control2=newLiteralControl();
102try
103{
104control2.Text=control3.GetType().GetProperty("SelectedItem").GetValue(control3,null).ToString();
105}
106catch(Exception)
107{
108}
109control.Controls.Add(control2);
110control.Controls.Remove(control3);
111}
112elseif(control3.GetType().GetProperty("Text")!=null)
113{
114control2=newLiteralControl();
115control2.Text=control3.GetType().GetProperty("Text").GetValue(control3,null).ToString();
116control.Controls.Add(control2);
117control.Controls.Remove(control3);
118}
119}
120}
121}
122}
123
124privatevoidCustomizePageBar(GridViewRowEventArgse)
125{
126
127Labellabel=newLabel();
128label.Text=(this.PageIndex+1)+"/"+this.PageCount;
129label.Font.Bold=true;
130
131TableCellcell2=newTableCell();
132cell2.Width=Unit.Pixel(80);
133cell2.Controls.Add(label);
134
135/**//*
136LabellbTotal=newLabel();
137lbTotal.Font.Bold=true;
138intcurrentPageIndex=this.PageIndex;
139this.PageIndex=this.PageCount-1;
140
141lbTotal.Text="共"+(this.PageCount-1)*this.PageSize+this.Rows.Count+"条记录";
142
143this.PageIndex=currentPageIndex;
144
145TableCellcellTotal=newTableCell();
146cellTotal.Width=Unit.Pixel(120);
147cellTotal.Controls.Add(lbTotal);
148*/
149
150
151
152LinkButtonlbtnFirst=newLinkButton();
153lbtnFirst.ID="lbtnfirst";
154lbtnFirst.Text="首页";
155lbtnFirst.Font.Bold=true;
156lbtnFirst.Font.Size=base.PagerStyle.Font.Size;
157lbtnFirst.Click+=newEventHandler(this.Pagination);
mandArgument="First";
159
160TableCellcellFirst=newTableCell();
161cellFirst.Width=Unit.Pixel(70);
162cellFirst.Controls.Add(lbtnFirst);
163
164LinkButtonlbtnPrev=newLinkButton();
165lbtnPrev.ID="lbtnprev";
166lbtnPrev.Text="上一页";
167lbtnPrev.Font.Bold=true;
168lbtnPrev.Font.Size=base.PagerStyle.Font.Size;
169lbtnPrev.Click+=newEventHandler(this.Pagination);
mandArgument="Prev";
171
172TableCellcellPrev=newTableCell();
173cellPrev.Width=Unit.Pixel(70);
174cellPrev.Controls.Add(lbtnPrev);
175
176LinkButtonlbtnNext=newLinkButton();
177lbtnNext.ID="lbtnnext";
178lbtnNext.Text="下一页";
179lbtnNext.Font.Bold=true;
180lbtnNext.Font.Size=base.PagerStyle.Font.Size;
181lbtnNext.Click+=newEventHandler(this.Pagination);
mandArgument="Next";
183
184TableCellcellNext=newTableCell();
185cellNext.Width=Unit.Pixel(70);
186cellNext.Controls.Add(lbtnNext);
187
188LinkButtonlbtnLast=newLinkButton();
189lbtnLast.ID="lbtnLast";
190lbtnLast.Text="末页";
191lbtnLast.Font.Bold=true;
192lbtnLast.Font.Size=base.PagerStyle.Font.Size;
193lbtnLast.Click+=newEventHandler(this.Pagination);
mandArgument="Last";
195
196TableCellcellLast=newTableCell();
197cellLast.Width=Unit.Pixel(70);
198cellLast.Controls.Add(lbtnLast);
199
200//cellFirst.Controls.Add(lbtnFirst);
201//cellFirst.Controls.Add(lbtnPrev);
202//cellFirst.Controls.Add(lbtnNext);
203//cellFirst.Controls.Add(lbtnLast);
204
205
206
207Labellabel2=newLabel();
208label2.Text="go:";
209label2.ID="lblGoTo";
210label2.Font.Bold=true;
211label2.Font.Size=base.PagerStyle.Font.Size;
212
213TableCellcell3=newTableCell();
214//cell3.Width=Unit.Pixel(0x10);
215
216cell3.Controls.Add(label2);
217
218
219DropDownListlist=newDropDownList();
220list.ID="ddlPick";
221list.AutoPostBack=true;
222list.EnableViewState=true;
223list.Font.Size=base.PagerStyle.Font.Size;
224
225for(inti=1;i<=this.PageCount;i++)
226{
227list.Items.Add(i.ToString());
228}
229list.SelectedIndex=this.PageIndex;
230list.SelectedIndexChanged+=newEventHandler(this.OnPagePicked);
231
232TextBoxtxtPage=newTextBox();
233txtPage.Text="";
234txtPage.Width=Unit.Pixel(20);
235txtPage.EnableViewState=true;
236txtPage.Font.Size=base.PagerStyle.Font.Size;
237
238
239TableCellcell4=newTableCell();
240//cell4.Width=Unit.Pixel(0x10);
241
242
243ButtonbtnOK=newButton();
244btnOK.ID="btnok";
245btnOK.Text="OK";
246btnOK.Click+=newEventHandler(this.OnbtnOK_Click);
247
248cell4.Controls.Add(txtPage);
249cell4.Controls.Add(btnOK);
250
251
252TableCellcell5=newTableCell();
253cell5.Width=Unit.Pixel(150);
254
255foreach(Controlcontroline.Row.Cells[0].Controls)
256{
257cell5.Controls.Add(control);
258}
259
260Tablechild=newTable();//
261child.BorderWidth=0;
262child.CellPadding=0;
263child.CellSpacing=0;
264child.Width=Unit.Percentage(100.0);
265child.Height=Unit.Pixel(20);
266
267child.Rows.Add(newTableRow());
268
269child.Rows[0].Cells.Add(cell2);
270
271//child.Rows[0].Cells.Add(cellTotal);
272child.Rows[0].Cells.Add(cellFirst);
273child.Rows[0].Cells.Add(cellPrev);
274child.Rows[0].Cells.Add(cellNext);
275child.Rows[0].Cells.Add(cellLast);
276
277child.Rows[0].Cells.Add(cell5);
278child.Rows[0].Cells.Add(cell3);
279child.Rows[0].Cells.Add(cell4);
280e.Row.Cells[0].Controls.Add(child);
281}
282
283protectedvoidDisplaySortOrderImages(stringsortExpression,GridViewRowdgItem)
284{
285string[]sortColumns=sortExpression.Split(",".ToCharArray());
286for(inti=0;i<dgItem.Cells.Count;i++)
287{
288if((dgItem.Cells[i].Controls.Count>0)&&(dgItem.Cells[i].Controls[0]isLinkButton))
289{
290stringstr;
291intnum2;
292stringcommandArgument=((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument;
293this.SearchSortExpression(sortColumns,commandArgument,outstr,outnum2);
294if(num2>0)
295{
296stringstr3=str.Equals("ASC")?this.SortAscImageUrl:this.SortDescImageUrl;
297if(str3!=string.Empty)
298{
299Imagechild=newImage();
300child.ImageUrl=str3;
301dgItem.Cells[i].Controls.Add(child);
302Labellabel=newLabel();
303label.Font.Size=FontUnit.Small;
304label.Text=num2.ToString();
305dgItem.Cells[i].Controls.Add(label);
306}
307else
308{
309Labellabel2=newLabel();
310label2.Font.Size=FontUnit.XSmall;
311label2.Font.Name="webdings";
312label2.EnableTheming=false;
313label2.Text=str.Equals("ASC")?"5":"6";
314dgItem.Cells[i].Controls.Add(label2);
315if(this.AllowMultiColumnSorting)
316{
317Literalliteral=newLiteral();
318literal.Text=num2.ToString();
319dgItem.Cells[i].Controls.Add(literal);
320}
321}
322}
323}
324}
325}
326
327protectedstringGetSortExpression(GridViewSortEventArgse)
328{
329string[]sortColumns=null;
330stringsortExpression=this.SortExpression;
331if(sortExpression!=string.Empty)
332{
333sortColumns=sortExpression.Split(",".ToCharArray());
334}
335if((sortExpression.IndexOf(e.SortExpression)>0)||sortExpression.StartsWith(e.SortExpression))
336{
337sortExpression=this.ModifySortExpression(sortColumns,e.SortExpression);
338}
339else
340{
341sortExpression=sortExpression+(","+e.SortExpression+"ASC");
342}
343returnsortExpression.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
344}
345
346protectedvoidimgToggle_Click(objectsender,ImageClickEventArgse)
347{
348ImageButtonbutton=(ImageButton)sender;
349GridViewparent=(GridView)button.Parent.Parent.Parent.Parent;
350
351parent.AllowPaging=!parent.AllowPaging;
352}
353
354protectedstringModifySortExpression(string[]sortColumns,stringsortExpression)
355{
356stringstr=sortExpression+"ASC";
357stringstr2=sortExpression+"DESC";
358for(inti=0;i<sortColumns.Length;i++)
359{
360if(str.Equals(sortColumns[i]))
361{
362sortColumns[i]=str2;
363}
364elseif(str2.Equals(sortColumns[i]))
365{
366Array.Clear(sortColumns,i,1);
367}
368}
369returnstring.Join(",",sortColumns).Replace(",,",",").TrimStart(",".ToCharArray());
370}
371
372protectedvoidOnPagePicked(objectsender,EventArgse)
373{
374DropDownListlist=(DropDownList)sender;
375this.PageIndex=Convert.ToInt32(list.SelectedItem.Value)-1;
376GridViewPageEventArgsargs=newGridViewPageEventArgs(Convert.ToInt32(list.SelectedItem.Value)-1);
377this.OnPageIndexChanging(args);
378}
379
380protectedvoidOnbtnOK_Click(objectsender,EventArgse)
381{
382
383//if(((Button)sender).Text.Trim()!="")
384//{
385
386//intintPageNo=Convert.ToInt32(((Button)sender).Text.Trim())-1;
387//if(intPageNo>0&&intPageNo<this.PageCount)
388//{
389//this.PageIndex=intPageNo;
390//GridViewPageEventArgsargs=newGridViewPageEventArgs(intPageNo);
391//this.OnPageIndexChanging(args);
392//}
393//}
394}
395
396protectedvoidPagination(objectsender,EventArgse)
397{
398LinkButtonlbtn=(LinkButton)sender;
399stringPageArgs=mandArgument;
400switch(PageArgs)
401{
402case"First":
403this.PageIndex=0;
404break;
405case"Prev":
406if(this.PageIndex>0)
407{
408this.PageIndex=this.PageIndex-1;
409}
410break;
411case"Next":
412if(this.PageIndex<this.PageCount-1)
413{
414this.PageIndex=this.PageIndex+1;
415}
416break;
417case"Last":
418this.PageIndex=this.PageCount-1;
419break;
420}
421GridViewPageEventArgsargs=newGridViewPageEventArgs(this.PageIndex);
422this.OnPageIndexChanging(args);
423
424
425}
426
427protectedoverridevoidOnRowCreated(GridViewRowEventArgse)
428{
429GridViewRowrow;
430if(e.Row.RowType==DataControlRowType.Header)
431{
432if(this.AllowPagingToggle)
433{
434ImageButtonchild=newImageButton();
435child.AlternateText="toggle";
436child.ImageUrl="~/images/toggle.gif";
437child.Click+=newImageClickEventHandler(this.imgToggle_Click);
438Imageimage=newImage();
439image.ImageUrl="~/images/spacer.gif";
440image.Width=10;
441ImageButtonbutton2=newImageButton();
442button2.AlternateText="excel";
443button2.ImageUrl="~/images/excel.gif";
444button2.Click+=newImageClickEventHandler(this.btnExport_Click);
445row=e.Row;
446row.Cells[0].Controls.Add(child);
447row.Cells[0].Controls.Add(image);
448row.Cells[0].Controls.Add(button2);
449}
450if(this.SortExpression!=string.Empty)
451{
452this.DisplaySortOrderImages(this.SortExpression,e.Row);
453}
454}
455elseif(e.Row.RowType==DataControlRowType.DataRow)
456{
457row=e.Row;
458boolflag=(row.RowIndex%2)==0;
459row.Attributes["onmouseover"]="HandleOver(this);";
460row.Attributes["onmouseout"]="HandleOut(this);";
461}
462elseif(e.Row.RowType==DataControlRowType.Pager)
463{
464this.CustomizePageBar(e);
465}
466base.OnRowCreated(e);
467}
468
469protectedoverridevoidOnRowDataBound(GridViewRowEventArgse)
470{
471if(e.Row.RowType==DataControlRowType.DataRow)
472{
473GridViewRowrow=e.Row;
474for(inti=0;i<row.Cells.Count;i++)
475{
476if(!string.IsNullOrEmpty(row.Cells[i].Text)&&char.IsNumber(row.Cells[i].Text[0]))
477{
478row.Cells[i].Attributes.Add("style","vnd.ms-excel.numberformat:@");
479}
480}
481}
482base.OnRowDataBound(e);
483}
484
485protectedoverridevoidOnSorting(GridViewSortEventArgse)
486{
487if(this.AllowMultiColumnSorting)
488{
489e.SortExpression=this.GetSortExpression(e);
490}
491base.OnSorting(e);
492}
493
494protectedvoidSearchSortExpression(string[]sortColumns,stringsortColumn,outstringsortOrder,outintsortOrderNo)
495{
496sortOrder="";
497sortOrderNo=-1;
498for(inti=0;i<sortColumns.Length;i++)
499{
500if(sortColumns[i].StartsWith(sortColumn))
501{
502sortOrderNo=i+1;
503if(this.AllowMultiColumnSorting)
504{
505sortOrder=sortColumns[i].Substring(sortColumn.Length).Trim();
506}
507else
508{
509sortOrder=(this.SortDirection==SortDirection.Ascending)?"ASC":"DESC";
510}
511}
512}
513}
514
515[DefaultValue("false"),Description("WhetherSortingOnmorethanonecolumnisenabled"),Category("Behavior")]
516publicboolAllowMultiColumnSorting
517{
518get
519{
520objectobj2=this.ViewState["EnableMultiColumnSorting"];
521return((obj2!=null)?((bool)obj2):false);
522}
523set
524{
525this.AllowSorting=true;
526this.ViewState["EnableMultiColumnSorting"]=value;
527}
528}
529
530[DefaultValue("true"),Description("WhetherPagingToggleisenabled"),Category("Behavior")]
531publicboolAllowPagingToggle
532{
533get
534{
535objectobj2=this.ViewState["AllowPagingToggle"];
536return((obj2!=null)?((bool)obj2):false);
537}
538set
539{
540this.ViewState["AllowPagingToggle"]=value;
541}
542}
543
544[DefaultValue(""),Editor("System.Web.UI.Design.UrlEditor",typeof(UITypeEditor)),Description("ImagetodisplayforAscendingSort"),Category("Misc")]
545publicstringSortAscImageUrl
546{
547get
548{
549objectobj2=this.ViewState["SortImageAsc"];
550return((obj2!=null)?obj2.ToString():"");
551}
552set
553{
554this.ViewState["SortImageAsc"]=value;
555}
556}
557
558[DefaultValue(""),Editor("System.Web.UI.Design.UrlEditor",typeof(UITypeEditor)),Description("ImagetodisplayforDescendingSort"),Category("Misc")]
559publicstringSortDescImageUrl
560{
561get
562{
563objectobj2=this.ViewState["SortImageDesc"];
564return((obj2!=null)?obj2.ToString():"");
565}
566set
567{
568this.ViewState["SortImageDesc"]=value;
569}
570}
571}
572}
如果觉得《自定义的GridView控件源代码》对你有帮助,请点赞、收藏,并留下你的观点哦!