温馨提示:代码在线浏览功能只能做为源码浏览参考,如果想更进一步了解该代码请下载:GridView自定义控件源码
当前文件:
GridViewControl/EntityGridView/bin/Release/EntityGridView .cs[26K,2009-6-12 11:43:30],打开代码结构图
GridViewControl/EntityGridView/bin/Release/EntityGridView .cs[26K,2009-6-12 11:43:30],打开代码结构图1using System; 2
using System.Collections.Generic; 3
using System.Text; 4
using System.Web.UI.WebControls; 5
using System.Web.UI; 6
using System.ComponentModel; 7
using System.IO; 8
9
namespace EntityGridView 10
...{ 11
12
public class EntityGridView : GridView 13
...{ 14
class member variables#region class member variables 15
private string _excelExportFileName = "Export.xls"; 16
private string _defaultSortColumnName = string.Empty; 17
private SortDirection _defaultSortDirection = SortDirection.Ascending; 18
private string _exportToExcelText = "Excel"; 19
private string _exportToolTip = string.Empty; 20
private bool _allowExportToExcel = true; 21
private int _pageSelectorPageSizeInterval = 10; 22
private TableRow _gridPagerRow = null; 23
#endregion 24
25
Properties#region Properties 26
/**//// <summary> 27
/// Set / Gets the Export File Name 28
/// </summary> 29
[ 30
Description("Set / Gets the Export File Name"), 31
Category("Misc"), 32
DefaultValue("Export.xls"), 33
] 34
public string ExcelExportFileName 35
...{ 36
get ...{ return _excelExportFileName; } 37
set ...{ _excelExportFileName = value; } 38
} 39
40
/**//// <summary> 41
/// Set / Gets the ToolTip 42
/// </summary> 43
[ 44
Description("et / Gets the ToolTip"), 45
Category("Misc"), 46
DefaultValue(""), 47
] 48
public string ExportToolTip 49
...{ 50
get ...{ return _exportToolTip; } 51
set ...{ _exportToolTip = value; } 52
} 53
54
/**//// <summary> 55
/// Gets / Sets Page Selector PageSize Interval 56
/// </summary> 57
[ 58
Description("Gets / Sets Page Selector PageSize Interval"), 59
Category("Misc"), 60
DefaultValue("10"), 61
] 62
public int PageSelectorPageSizeInterval 63
...{ 64
get ...{ return _pageSelectorPageSizeInterval; } 65
set ...{ _pageSelectorPageSizeInterval = value; } 66
} 67
68
/**//// <summary> 69
/// Get / Sest the Export to excel text 70
/// </summary> 71
[ 72
Description("Gets / Sets the Export to Excel Text"), 73
Category("Misc"), 74
DefaultValue("Export"), 75
] 76
public string ExportToExcelText 77
...{ 78
get 79
...{ 80
return _exportToExcelText; 81
} 82
set 83
...{ 84
_exportToExcelText = value; 85
} 86
} 87
88
/**//// <summary> 89
/// Enable/Disable ExportToExcel 90
/// </summary> 91
[ 92
Description("Whether Exporting Or Not to Excel file"), 93
Category("Behavior"), 94
DefaultValue("true"), 95
] 96
public bool AllowExportToExcel 97
...{ 98
get ...{ return _allowExportToExcel; } 99
set ...{ _allowExportToExcel = value; } 100
} 101
102
/**//// <summary> 103
/// Sets / Gets Default Sort Column Name 104
/// </summary> 105
[ 106
Description("Sets / Gets Default Sort Column Name"), 107
Category("Behavior"), 108
DefaultValue(""), 109
] 110
public string DefaultSortColumnName 111
...{ 112
get 113
...{ 114
return (_defaultSortColumnName == string.Empty) ? GetDefaultSortColumn() : _defaultSortColumnName; 115
116
} 117
set ...{ _defaultSortColumnName = value; } 118
} 119
120
/**//// <summary> 121
/// Setting the default sort order direction 122
/// </summary> 123
[ 124
Description("Default Sort Order Direction"), 125
Category("Misc"), 126
Editor("System.Web.UI.WebControls.SortDirection", typeof(System.Web.UI.WebControls.SortDirection)), 127
DefaultValue("SortDirection.Ascending"), 128
] 129
public SortDirection DefaultSortDirection 130
...{ 131
get ...{ return _defaultSortDirection; } 132
set ...{ _defaultSortDirection = value; } 133
} 134
135
/**//// <summary> 136
/// Enable/Disable MultiColumn Sorting. 137
/// </summary> 138
[ 139
Description("Whether Sorting On more than one column is enabled"), 140
Category("Behavior"), 141
DefaultValue("false"), 142
] 143
public bool AllowMultiColumnSorting 144
...{ 145
get 146
...{ 147
object o = ViewState["EnableMultiColumnSorting"]; 148
return (o != null ? (bool)o : false); 149
} 150
set 151
...{ 152
AllowSorting = true; 153
ViewState["EnableMultiColumnSorting"] = value; 154
} 155
} 156
/**//// <summary> 157
/// Get or Set Image location to be used to display Ascending Sort order. 158
/// </summary> 159
[ 160
Description("Image to display for Ascending Sort"), 161
Category("Misc"), 162
Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)), 163
DefaultValue(""), 164
] 165
public string SortAscImageUrl 166
...{ 167
get 168
...{ 169
object o = ViewState["SortImageAsc"]; 170
return (o != null ? o.ToString() : ""); 171
} 172
set 173
...{ 174
ViewState["SortImageAsc"] = value; 175
} 176
} 177
/**//// <summary> 178
/// Get or Set Image location to be used to display Ascending Sort order. 179
/// </summary> 180
[ 181
Description("Image to display for Descending Sort"), 182
Category("Misc"), 183
Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)), 184
DefaultValue(""), 185
] 186
public string SortDescImageUrl 187
...{ 188
get 189
...{ 190
object o = ViewState["SortImageDesc"]; 191
return (o != null ? o.ToString() : ""); 192
} 193
set 194
...{ 195
ViewState["SortImageDesc"] = value; 196
} 197
} 198
199
/**//// <summary> 200
/// Total Records Count being assigned the value in the DataSource_Selected event 201
/// </summary> 202
protected int RecordsCount 203
...{ 204
get 205
...{ 206
if (ViewState["_recordsCount"] != null) 207
return (int)ViewState["_recordsCount"]; 208
else 209
return 0; 210
} 211
set 212
...{ 213
ViewState["_recordsCount"] = value; 214
} 215
} 216
#endregion 217
218
Life Cycle#region Life Cycle 219
220
/**//// <summary> 221
/// Occurs when the server control is initialized. 222
/// </summary> 223
/// <param name="e"></param> 224
protected override void OnInit(EventArgs e) 225
...{ 226
base.OnInit(e); 227
228
if (Page.IsPostBack == false) 229
...{ 230
this.Sort(DefaultSortColumnName, _defaultSortDirection); 231
} 232
233
DataSourceControl dsc = (DataSourceControl)this.Parent.FindControl(string.Format("{0}", this.DataSourceID)); 234
235
System.Reflection.EventInfo eventInfo = dsc.GetType().GetEvent("Selected"); 236
Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, "dsc_Selected"); 237
238
eventInfo.AddEventHandler(dsc, d); 239
240
} 241
242
void dsc_Selected(object sender, SqlDataSourceStatusEventArgs e) 243
...{ 244
RecordsCount = e.AffectedRows; 245
} 246
247
void dsc_Selected(object sender, ObjectDataSourceStatusEventArgs e) 248
...{ 249
RecordsCount = e.AffectedRows; 250
} 251
252
253
/**//// <summary> 254
/// Occurs when the hyperlink to sort a column is clicked, but before the EntityGridView control handles the sort operation. 255
/// </summary> 256
/// <param name="e"></param> 257
protected override void OnSorting(GridViewSortEventArgs e) 258
...{ 259
if (AllowMultiColumnSorting) 260
e.SortExpression = GetSortExpression(e); 261
262
base.OnSorting(e); 263
} 264
265
/**//// <summary> 266
/// Occurs when a row is created in a GridView control. 267
/// </summary> 268
/// <param name="e"></param> 269
protected override void OnRowCreated(GridViewRowEventArgs e) 270
...{ 271
base.OnRowCreated(e); 272
if (e.Row.RowType == DataControlRowType.Header) 273
...{ 274
if (SortExpression != String.Empty) 275
DisplaySortOrderImages(SortExpression, e.Row); 276
} 277
else if (e.Row.RowType == DataControlRowType.Pager) 278
...{ 279
DisplayPageSizeSelector(e.Row); 280
_gridPagerRow = e.Row; 281
} 282
} 283
284
285
/**//// <summary> 286
/// Occurs after the Control object is loaded but prior to rendering. 287
/// </summary> 288
/// <param name="e"></param> 289
protected override void OnPreRender(EventArgs e) 290
...{ 291
base.OnPreRender(e); 292
293
if (this.RecordsCount > 0 && this.AllowPaging) 294
_gridPagerRow.Visible = true; 295
} 296
#endregion 297
298
Help Methonds#region Help Methonds 299
/**//// <summary> 300
/// Determining the first column in the column collection that has SortExpression value set, and using this column as a default sort column 301
/// </summary> 302
/// <returns></returns> 303
protected string GetDefaultSortColumn() 304
...{ 305
string SortColumnName = string.Empty; 306
307
for (int i = 0; i < this.Columns.Count; i++) 308
...{ 309
SortColumnName = this.Columns[i].SortExpression; 310
if (SortColumnName != string.Empty) 311
...{ 312
break; 313
} 314
} 315
316
return SortColumnName; 317
} 318
319
private void DisplayPageSizeSelector(GridViewRow dgItem) 320
...{ 321
TableCell pagerCell; 322
TableRow pagerRow; 323
324
int j = 0; 325
System.Web.UI.WebControls.DropDownList cboPageSize = new DropDownList(); 326
cboPageSize.AutoPostBack = true; 327
328
((DropDownList)(cboPageSize)).SelectedIndexChanged += new EventHandler(this.cboPageSize_SelectedIndexChanged); 329
330
// -- we don't want to allow to page more then 500 records at a time 331
j = this.RecordsCount + _pageSelectorPageSizeInterval; 332
for (int i = _pageSelectorPageSizeInterval; i <= ((j > 250) ? 250 : j); ) 333
...{ 334
cboPageSize.Items.Add(i.ToString()); 335
i += _pageSelectorPageSizeInterval; 336
} 337
338
if (cboPageSize.Items.FindByText(this.PageSize.ToString()) != null) 339
...{ 340
cboPageSize.Items.FindByText(this.PageSize.ToString()).Selected = true; 341
} 342
343
pagerRow = dgItem; 344
pagerCell = ((TableCell)(pagerRow.Controls[0])); 345
TableRow pagerTableRow = ((Table)pagerCell.Controls[0]).Rows[0]; 346
TableCell cell = new TableCell(); 347
cell.Text = "Show page: "; 348
cell.Wrap = false; 349
pagerTableRow.Cells.AddAt(0, cell); 350
351
cell = new TableCell(); 352
cell.Text = string.Format(" (Total Records: {0})", RecordsCount); 353
cell.Wrap = false; 354
pagerTableRow.Cells.Add(cell); 355
356
cell = new TableCell(); 357
cell.Width = Unit.Percentage(100); 358
pagerTableRow.Cells.Add(cell); 359
360
if (AllowExportToExcel) 361
...{ 362
cell = new TableCell(); 363
cell.Controls.Add(ExcelButton()); 364
cell.Wrap = false; 365
pagerTableRow.Cells.Add(cell); 366
} 367
368
cell = new TableCell(); 369
cell.Text = "Records Per Page: "; 370
cell.Wrap = false; 371
cell.HorizontalAlign = HorizontalAlign.Right; 372
pagerTableRow.Cells.Add(cell); 373
374
cell = new TableCell(); 375
cell.Controls.Add(cboPageSize); 376
cell.HorizontalAlign = HorizontalAlign.Right; 377
pagerTableRow.Cells.Add(cell); 378
} 379
380
private LinkButton ExcelButton() 381
...{ 382
LinkButton lnkExport = new LinkButton(); 383
lnkExport.ToolTip = _exportToolTip; 384
lnkExport.Text = _exportToExcelText; 385
lnkExport.Click += new EventHandler(lnkExport_Click); 386
387
return lnkExport; 388
} 389
#endregion 390
391
Controls Events#region Controls Events 392
/**//// <summary> 393
/// Exporting all the records by rebinding the gridview and re-setting the page index 394
/// </summary> 395
/// <param name="sender"></param> 396
/// <param name="e"></param> 397
void lnkExport_Click(object sender, EventArgs e) 398
...{ 399
this.AllowMultiColumnSorting = false; 400
this.AllowPaging = false; 401
this.AllowSorting = false; 402
this.ShowFooter = false; 403
this.EnableViewState = false; 404
405
this.PageIndex = 0; 406
this.PageSize = this.RecordsCount; 407
this.DataSourceID = this.DataSourceID; 408
this.DataBind(); 409
410
GridViewExcelExporter exp = new GridViewExcelExporter(); 411
exp.Export(_excelExportFileName, this.Page, this); 412
} 413
414
415
416
cboPageSize_SelectedIndexChanged#region cboPageSize_SelectedIndexChanged 417
/**//// <summary> 418
/// Occurs when the value of the SelectedIndex property changes. 419
/// </summary> 420
private void cboPageSize_SelectedIndexChanged(object sender, System.EventArgs e) 421
...{ 422
// -- reset current page index to 0, that is nessessary so that there won't be a situation when datagrid current page index is off causing an exception 423
this.PageIndex = 0; 424
DropDownList cboPageSize = (DropDownList)sender; 425
this.PageSize = int.Parse(cboPageSize.SelectedValue); 426
} 427
#endregion 428
429
#endregion 430
431
Protected Methods#region Protected Methods 432
/**//// <summary> 433
/// Get Sort Expression by Looking up the existing Grid View Sort Expression 434
/// </summary> 435
protected string GetSortExpression(GridViewSortEventArgs e) 436
...{ 437
string[] sortColumns = null; 438
string sortAttribute = SortExpression; 439
440
//Check to See if we have an existing Sort Order already in the Grid View. 441
//If so get the Sort Columns into an array 442
if (sortAttribute != String.Empty) 443
...{ 444
sortColumns = sortAttribute.Split(",".ToCharArray()); 445
} 446
447
//if User clicked on the columns in the existing sort sequence. 448
//Toggle the sort order or remove the column from sort appropriately 449
450
if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression)) 451
sortAttribute = ModifySortExpression(sortColumns, e.SortExpression); 452
else 453
sortAttribute += String.Concat(",", e.SortExpression, " ASC "); 454
return sortAttribute.TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray()); 455
456
} 457
/**//// <summary> 458
/// Toggle the sort order or remove the column from sort appropriately 459
/// </summary> 460
protected string ModifySortExpression(string[] sortColumns, string sortExpression) 461
...{ 462
463
string ascSortExpression = String.Concat(sortExpression, " ASC "); 464
string descSortExpression = String.Concat(sortExpression, " DESC "); 465
466
for (int i = 0; i < sortColumns.Length; i++) 467
...{ 468
469
if (ascSortExpression.Equals(sortColumns[i])) 470
...{ 471
sortColumns[i] = descSortExpression; 472
} 473
474
else if (descSortExpression.Equals(sortColumns[i])) 475
...{ 476
Array.Clear(sortColumns, i, 1); 477
} 478
} 479
480
return String.Join(",", sortColumns).Replace(",,", ",").TrimStart(",".ToCharArray()); 481
482
} 483
/**//// <summary> 484
/// Lookup the Current Sort Expression to determine the Order of a specific item. 485
/// </summary> 486
protected void SearchSortExpression(string[] sortColumns, string sortColumn, out string sortOrder, out int sortOrderNo) 487
...{ 488
sortOrder = ""; 489
sortOrderNo = -1; 490
for (int i = 0; i < sortColumns.Length; i++) 491
...{ 492
if (sortColumns[i].StartsWith(sortColumn)) 493
...{ 494
sortOrderNo = i + 1; 495
if (AllowMultiColumnSorting) 496
sortOrder = sortColumns[i].Substring(sortColumn.Length).Trim(); 497
else 498
sortOrder = ((SortDirection == SortDirection.Ascending) ? "ASC" : "DESC"); 499
} 500
} 501
} 502
/**//// <summary> 503
/// Display a graphic image for the Sort Order along with the sort sequence no. 504
/// </summary> 505
protected void DisplaySortOrderImages(string sortExpression, GridViewRow dgItem) 506
...{ 507
string[] sortColumns = sortExpression.Split(",".ToCharArray()); 508
509
for (int i = 0; i < dgItem.Cells.Count; i++) 510
...{ 511
if (dgItem.Cells[i].Controls.Count > 0 && dgItem.Cells[i].Controls[0] is LinkButton) 512
...{ 513
string sortOrder; 514
int sortOrderNo; 515
string column = ((LinkButton)dgItem.Cells[i].Controls[0]).CommandArgument; 516
SearchSortExpression(sortColumns, column, out sortOrder, out sortOrderNo); 517
if (sortOrderNo > 0) 518
...{ 519
string sortImgLoc = (sortOrder.Equals("ASC") ? SortAscImageUrl : SortDescImageUrl); 520
521
if (sortImgLoc != String.Empty) 522
...{ 523
Image imgSortDirection = new Image(); 524
imgSortDirection.ImageUrl = sortImgLoc; 525
dgItem.Cells[i].Controls.Add(imgSortDirection); 526
Label lblSortOrder = new Label(); 527
lblSortOrder.Font.Size = FontUnit.Small; 528
lblSortOrder.Text = sortOrderNo.ToString(); 529
dgItem.Cells[i].Controls.Add(lblSortOrder); 530
531
} 532
else 533
...{ 534
535
Label lblSortDirection = new Label(); 536
lblSortDirection.Font.Size = FontUnit.XSmall; 537
lblSortDirection.Font.Name = "webdings"; 538
lblSortDirection.EnableTheming = false; 539
lblSortDirection.Text = (sortOrder.Equals("ASC") ? "5" : "6"); 540
dgItem.Cells[i].Controls.Add(lblSortDirection); 541
542
if (AllowMultiColumnSorting) 543
...{ 544
Literal litSortSeq = new Literal(); 545
litSortSeq.Text = sortOrderNo.ToString(); 546
dgItem.Cells[i].Controls.Add(litSortSeq); 547
548
} 549
} 550
} 551
} 552
} 553
} 554
#endregion 555
} 556
557
Excel Export Implementation#region Excel Export Implementation 558
559
560
/**//// <summary> 561
/// Exports a gridview to a excel file. 562
/// </summary> 563
/// <requirements>Microsoft Excel 97 or above should be installed on the client machine in order to make 564
/// this function work 565
/// </requirements> 566
public class GridViewExcelExporter 567
...{ 568
/**//// <summary> 569
/// Ctor of the GridViewExcelExporter class 570
/// </summary> 571
public GridViewExcelExporter() 572
...{ 573
} 574
575
576
/**//// <summary> 577
/// Exports the datagrid to an Excel file with the name of the datasheet provided by the passed in parameter 578
/// </summary> 579
public virtual void Export(string reportName, Page CurrentPage, Control NtGridView) 580
...{ 581
System.Web.UI.HtmlControls.HtmlForm htmlForm = new System.Web.UI.HtmlControls.HtmlForm(); 582
CurrentPage.Controls.Add(htmlForm); 583
htmlForm.Controls.Add(NtGridView); 584
585
ClearChildControls((GridView)NtGridView); 586
587
CurrentPage.Response.Clear(); 588
CurrentPage.Response.Buffer = true; 589
590
CurrentPage.Response.AddHeader("Content-Disposition", "attachment; filename=" + reportName); 591
CurrentPage.Response.ContentType = "application/vnd.ms-excel"; 592
CurrentPage.Response.ContentEncoding = System.Text.Encoding.UTF8; 593
CurrentPage.Response.Charset = ""; 594
CurrentPage.EnableViewState = false; 595
596
using (StringWriter stringWriter = new StringWriter()) 597
...{ 598
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); 599
htmlForm.RenderControl(htmlWriter); 600
htmlWriter.Flush(); 601
602
CurrentPage.Response.Write(stringWriter.ToString()); 603
CurrentPage.Response.End(); 604
} 605
} 606
607
/**//// <summary> 608
/// Iterates a control and its children controls, ensuring they are all LiteralControls 609
/// <remarks> 610
/// Only LiteralControl can call RenderControl(System.Web.UI.HTMLTextWriter htmlWriter) method. Otherwise 611
/// a runtime error will occur. This is the reason why this method exists. 612
/// </remarks> 613
/// </summary> 614
/// <param name="control">The control to be cleared and verified</param> 615
private void RecursiveClear(Control control) 616
...{ 617
//Clears children controls 618
for (int i = control.Controls.Count - 1; i >= 0; i--) 619
...{ 620
RecursiveClear(control.Controls[i]); 621
} 622
623
if (control is Repeater) 624
...{ 625
// TODO: handle repeater control displayed item when used with EntityDataSourceFilter control 626
control.Parent.Controls.Remove(control); 627
} 628
//If it is a LinkButton, convert it to a LiteralControl 629
else if (control is LinkButton) 630
...{ 631
LiteralControl literal = new LiteralControl(); 632
control.Parent.Controls.Add(literal); 633
literal.Text = ((LinkButton)control).Text; 634
control.Parent.Controls.Remove(control); 635
} 636
//We don't need a button in the excel sheet, so simply delete it 637
else if (control is Button) 638
...{ 639
control.Parent.Controls.Remove(control); 640
} 641
642
else if (control is Image) 643
...{ 644
if (((Image)control).Visible) 645
...{ 646
control.Parent.Controls.Add(new LiteralControl("<span style='font-size:8px;'>o</span>")); 647
} 648
control.Parent.Controls.Remove(control); 649
} 650
//If it is a ListControl, copy the text to a new LiteralControl 651
else if (control is ListControl) 652
...{ 653
LiteralControl literal = new LiteralControl(); 654
control.Parent.Controls.Add(literal); 655
try 656
...{ 657
literal.Text = ((ListControl)control).SelectedItem.Text; 658
} 659
catch 660
...{ 661
} 662
control.Parent.Controls.Remove(control); 663
664
} 665
//You may add more conditions when necessary 666
667
return; 668
} 669
670
/**//// <summary> 671
/// Clears the child controls of a EntityGridView to make sure all controls are LiteralControls 672
/// </summary> 673
/// <param name="dg">Datagrid to be cleared and verified</param> 674
protected void ClearChildControls(System.Web.UI.WebControls.GridView dg) 675
...{ 676
677
for (int i = dg.Columns.Count - 1; i >= 0; i--) 678
...{ 679
if (dg.Columns[i].GetType().Name == "ButtonColumn" 680
|| dg.Columns[i].GetType().Name == "CheckBoxField" 681
|| dg.Columns[i].GetType().Name == "CommandField") 682
...{ 683
dg.Columns[i].Visible = false; 684
} 685
} 686
687
this.RecursiveClear(dg); 688
} 689
} 690
} 691
692
#endregion






}