2006-10-12 Igor Zelmanovich <igorz@mainsoft.com>
[mono.git] / mcs / class / System.Web / System.Web.UI.WebControls / GridView.cs
1 //
2 // System.Web.UI.WebControls.GridView.cs
3 //
4 // Authors:
5 //      Lluis Sanchez Gual (lluis@novell.com)
6 //
7 // (C) 2005 Novell, Inc (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28
29 #if NET_2_0
30
31 using System;
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.ComponentModel;
35 using System.Web.UI;
36 using System.Security.Permissions;
37 using System.Text;
38 using System.IO;
39 using System.Reflection;
40
41 namespace System.Web.UI.WebControls
42 {
43         [SupportsEventValidation]
44         [DesignerAttribute ("System.Web.UI.Design.WebControls.GridViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
45         [ControlValuePropertyAttribute ("SelectedValue")]
46         [DefaultEventAttribute ("SelectedIndexChanged")]
47         [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48         [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
49         public class GridView: CompositeDataBoundControl, ICallbackEventHandler, ICallbackContainer, IPostBackEventHandler, IPostBackContainer
50         {
51                 Table table;
52                 GridViewRowCollection rows;
53                 GridViewRow bottomPagerRow;
54                 GridViewRow topPagerRow;
55                 
56                 IOrderedDictionary currentEditRowKeys;
57                 IOrderedDictionary currentEditNewValues;
58                 IOrderedDictionary currentEditOldValues;
59                 
60                 ITemplate pagerTemplate;
61                 ITemplate emptyDataTemplate;
62                 
63                 PropertyDescriptor[] cachedKeyProperties;
64                         
65                 // View state
66                 DataControlFieldCollection columns;
67                 PagerSettings pagerSettings;
68                 
69                 TableItemStyle alternatingRowStyle;
70                 TableItemStyle editRowStyle;
71                 TableItemStyle emptyDataRowStyle;
72                 TableItemStyle footerStyle;
73                 TableItemStyle headerStyle;
74                 TableItemStyle pagerStyle;
75                 TableItemStyle rowStyle;
76                 TableItemStyle selectedRowStyle;
77                 DataKeyArray keys;
78                 DataKey oldEditValues;
79                 AutoGeneratedFieldProperties[] autoFieldProperties;
80                 string [] dataKeyNames = null;
81                 readonly string[] emptyKeys = new string[0];
82                 
83                 private static readonly object PageIndexChangedEvent = new object();
84                 private static readonly object PageIndexChangingEvent = new object();
85                 private static readonly object RowCancelingEditEvent = new object();
86                 private static readonly object RowCommandEvent = new object();
87                 private static readonly object RowCreatedEvent = new object();
88                 private static readonly object RowDataBoundEvent = new object();
89                 private static readonly object RowDeletedEvent = new object();
90                 private static readonly object RowDeletingEvent = new object();
91                 private static readonly object RowEditingEvent = new object();
92                 private static readonly object RowUpdatedEvent = new object();
93                 private static readonly object RowUpdatingEvent = new object();
94                 private static readonly object SelectedIndexChangedEvent = new object();
95                 private static readonly object SelectedIndexChangingEvent = new object();
96                 private static readonly object SortedEvent = new object();
97                 private static readonly object SortingEvent = new object();
98                 
99                 // Control state
100                 int pageIndex;
101                 int pageCount;
102                 int selectedIndex = -1;
103                 int editIndex = -1;
104                 SortDirection sortDirection = SortDirection.Ascending;
105                 string sortExpression;
106                 
107                 public GridView ()
108                 {
109                 }
110                 
111                 public event EventHandler PageIndexChanged {
112                         add { Events.AddHandler (PageIndexChangedEvent, value); }
113                         remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
114                 }
115                 
116                 public event GridViewPageEventHandler PageIndexChanging {
117                         add { Events.AddHandler (PageIndexChangingEvent, value); }
118                         remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
119                 }
120                 
121                 public event GridViewCancelEditEventHandler RowCancelingEdit {
122                         add { Events.AddHandler (RowCancelingEditEvent, value); }
123                         remove { Events.RemoveHandler (RowCancelingEditEvent, value); }
124                 }
125                 
126                 public event GridViewCommandEventHandler RowCommand {
127                         add { Events.AddHandler (RowCommandEvent, value); }
128                         remove { Events.RemoveHandler (RowCommandEvent, value); }
129                 }
130                 
131                 public event GridViewRowEventHandler RowCreated {
132                         add { Events.AddHandler (RowCreatedEvent, value); }
133                         remove { Events.RemoveHandler (RowCreatedEvent, value); }
134                 }
135                 
136                 public event GridViewRowEventHandler RowDataBound {
137                         add { Events.AddHandler (RowDataBoundEvent, value); }
138                         remove { Events.RemoveHandler (RowDataBoundEvent, value); }
139                 }
140                 
141                 public event GridViewDeletedEventHandler RowDeleted {
142                         add { Events.AddHandler (RowDeletedEvent, value); }
143                         remove { Events.RemoveHandler (RowDeletedEvent, value); }
144                 }
145                 
146                 public event GridViewDeleteEventHandler RowDeleting {
147                         add { Events.AddHandler (RowDeletingEvent, value); }
148                         remove { Events.RemoveHandler (RowDeletingEvent, value); }
149                 }
150                 
151                 public event GridViewEditEventHandler RowEditing {
152                         add { Events.AddHandler (RowEditingEvent, value); }
153                         remove { Events.RemoveHandler (RowEditingEvent, value); }
154                 }
155                 
156                 public event GridViewUpdatedEventHandler RowUpdated {
157                         add { Events.AddHandler (RowUpdatedEvent, value); }
158                         remove { Events.RemoveHandler (RowUpdatedEvent, value); }
159                 }
160                 
161                 public event GridViewUpdateEventHandler RowUpdating {
162                         add { Events.AddHandler (RowUpdatingEvent, value); }
163                         remove { Events.RemoveHandler (RowUpdatingEvent, value); }
164                 }
165                 
166                 public event EventHandler SelectedIndexChanged {
167                         add { Events.AddHandler (SelectedIndexChangedEvent, value); }
168                         remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
169                 }
170                 
171                 public event GridViewSelectEventHandler SelectedIndexChanging {
172                         add { Events.AddHandler (SelectedIndexChangingEvent, value); }
173                         remove { Events.RemoveHandler (SelectedIndexChangingEvent, value); }
174                 }
175                 
176                 public event EventHandler Sorted {
177                         add { Events.AddHandler (SortedEvent, value); }
178                         remove { Events.RemoveHandler (SortedEvent, value); }
179                 }
180                 
181                 public event GridViewSortEventHandler Sorting {
182                         add { Events.AddHandler (SortingEvent, value); }
183                         remove { Events.RemoveHandler (SortingEvent, value); }
184                 }
185                 
186                 protected virtual void OnPageIndexChanged (EventArgs e)
187                 {
188                         if (Events != null) {
189                                 EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
190                                 if (eh != null) eh (this, e);
191                         }
192                 }
193                 
194                 protected virtual void OnPageIndexChanging (GridViewPageEventArgs e)
195                 {
196                         if (Events != null) {
197                                 GridViewPageEventHandler eh = (GridViewPageEventHandler) Events [PageIndexChangingEvent];
198                                 if (eh != null) eh (this, e);
199                         }
200                 }
201                 
202                 protected virtual void OnRowCancelingEdit (GridViewCancelEditEventArgs e)
203                 {
204                         if (Events != null) {
205                                 GridViewCancelEditEventHandler eh = (GridViewCancelEditEventHandler) Events [RowCancelingEditEvent];
206                                 if (eh != null) eh (this, e);
207                         }
208                 }
209                 
210                 protected virtual void OnRowCommand (GridViewCommandEventArgs e)
211                 {
212                         if (Events != null) {
213                                 GridViewCommandEventHandler eh = (GridViewCommandEventHandler) Events [RowCommandEvent];
214                                 if (eh != null) eh (this, e);
215                         }
216                 }
217                 
218                 protected virtual void OnRowCreated (GridViewRowEventArgs e)
219                 {
220                         if (Events != null) {
221                                 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowCreatedEvent];
222                                 if (eh != null) eh (this, e);
223                         }
224                 }
225                 
226                 protected virtual void OnRowDataBound (GridViewRowEventArgs e)
227                 {
228                         if (Events != null) {
229                                 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowDataBoundEvent];
230                                 if (eh != null) eh (this, e);
231                         }
232                 }
233                 
234                 protected virtual void OnRowDeleted (GridViewDeletedEventArgs e)
235                 {
236                         if (Events != null) {
237                                 GridViewDeletedEventHandler eh = (GridViewDeletedEventHandler) Events [RowDeletedEvent];
238                                 if (eh != null) eh (this, e);
239                         }
240                 }
241                 
242                 protected virtual void OnRowDeleting (GridViewDeleteEventArgs e)
243                 {
244                         if (Events != null) {
245                                 GridViewDeleteEventHandler eh = (GridViewDeleteEventHandler) Events [RowDeletingEvent];
246                                 if (eh != null) eh (this, e);
247                         }
248                 }
249                 
250                 protected virtual void OnRowEditing (GridViewEditEventArgs e)
251                 {
252                         if (Events != null) {
253                                 GridViewEditEventHandler eh = (GridViewEditEventHandler) Events [RowEditingEvent];
254                                 if (eh != null) eh (this, e);
255                         }
256                 }
257                 
258                 protected virtual void OnRowUpdated (GridViewUpdatedEventArgs e)
259                 {
260                         if (Events != null) {
261                                 GridViewUpdatedEventHandler eh = (GridViewUpdatedEventHandler) Events [RowUpdatedEvent];
262                                 if (eh != null) eh (this, e);
263                         }
264                 }
265                 
266                 protected virtual void OnRowUpdating (GridViewUpdateEventArgs e)
267                 {
268                         if (Events != null) {
269                                 GridViewUpdateEventHandler eh = (GridViewUpdateEventHandler) Events [RowUpdatingEvent];
270                                 if (eh != null) eh (this, e);
271                         }
272                 }
273                 
274                 protected virtual void OnSelectedIndexChanged (EventArgs e)
275                 {
276                         if (Events != null) {
277                                 EventHandler eh = (EventHandler) Events [SelectedIndexChangedEvent];
278                                 if (eh != null) eh (this, e);
279                         }
280                 }
281                 
282                 protected virtual void OnSelectedIndexChanging (GridViewSelectEventArgs e)
283                 {
284                         if (Events != null) {
285                                 GridViewSelectEventHandler eh = (GridViewSelectEventHandler) Events [SelectedIndexChangingEvent];
286                                 if (eh != null) eh (this, e);
287                         }
288                 }
289                 
290                 protected virtual void OnSorted (EventArgs e)
291                 {
292                         if (Events != null) {
293                                 EventHandler eh = (EventHandler) Events [SortedEvent];
294                                 if (eh != null) eh (this, e);
295                         }
296                 }
297                 
298                 protected virtual void OnSorting (GridViewSortEventArgs e)
299                 {
300                         if (Events != null) {
301                                 GridViewSortEventHandler eh = (GridViewSortEventHandler) Events [SortingEvent];
302                                 if (eh != null) eh (this, e);
303                         }
304                 }
305                 
306                 
307                 [WebCategoryAttribute ("Paging")]
308                 [DefaultValueAttribute (false)]
309                 public virtual bool AllowPaging {
310                         get {
311                                 object ob = ViewState ["AllowPaging"];
312                                 if (ob != null) return (bool) ob;
313                                 return false;
314                         }
315                         set {
316                                 ViewState ["AllowPaging"] = value;
317                                 RequireBinding ();
318                         }
319                 }
320                 
321                 [WebCategoryAttribute ("Behavior")]
322                 [DefaultValueAttribute (false)]
323                 public virtual bool AllowSorting {
324                         get {
325                                 object ob = ViewState ["AllowSorting"];
326                                 if (ob != null) return (bool) ob;
327                                 return false;
328                         }
329                         set {
330                                 ViewState ["AllowSorting"] = value;
331                                 RequireBinding ();
332                         }
333                 }
334                 
335                 [WebCategoryAttribute ("Styles")]
336                 [PersistenceMode (PersistenceMode.InnerProperty)]
337                 [NotifyParentProperty (true)]
338                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
339                 public TableItemStyle AlternatingRowStyle {
340                         get {
341                                 if (alternatingRowStyle == null) {
342                                         alternatingRowStyle = new TableItemStyle ();
343                                         if (IsTrackingViewState)
344                                                 alternatingRowStyle.TrackViewState();
345                                 }
346                                 return alternatingRowStyle;
347                         }
348                 }
349
350                 [WebCategoryAttribute ("Behavior")]
351                 [DefaultValueAttribute (false)]
352                 public virtual bool AutoGenerateEditButton {
353                         get {
354                                 object ob = ViewState ["AutoGenerateEditButton"];
355                                 if (ob != null) return (bool) ob;
356                                 return false;
357                         }
358                         set {
359                                 ViewState ["AutoGenerateEditButton"] = value;
360                                 RequireBinding ();
361                         }
362                 }
363
364                 [WebCategoryAttribute ("Behavior")]
365                 [DefaultValueAttribute (false)]
366                 public virtual bool AutoGenerateDeleteButton {
367                         get {
368                                 object ob = ViewState ["AutoGenerateDeleteButton"];
369                                 if (ob != null) return (bool) ob;
370                                 return false;
371                         }
372                         set {
373                                 ViewState ["AutoGenerateDeleteButton"] = value;
374                                 RequireBinding ();
375                         }
376                 }
377
378                 [WebCategoryAttribute ("Behavior")]
379                 [DefaultValueAttribute (false)]
380                 public virtual bool AutoGenerateSelectButton {
381                         get {
382                                 object ob = ViewState ["AutoGenerateSelectButton"];
383                                 if (ob != null) return (bool) ob;
384                                 return false;
385                         }
386                         set {
387                                 ViewState ["AutoGenerateSelectButton"] = value;
388                                 RequireBinding ();
389                         }
390                 }
391
392                 [WebCategoryAttribute ("Behavior")]
393                 [DefaultValueAttribute (true)]
394                 public virtual bool AutoGenerateColumns {
395                         get {
396                                 object ob = ViewState ["AutoGenerateColumns"];
397                                 if (ob != null) return (bool) ob;
398                                 return true;
399                         }
400                         set {
401                                 ViewState ["AutoGenerateColumns"] = value;
402                                 RequireBinding ();
403                         }
404                 }
405                 
406                 [UrlPropertyAttribute]
407                 [WebCategoryAttribute ("Appearance")]
408                 [DefaultValueAttribute ("")]
409                 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
410                 public virtual string BackImageUrl {
411                         get {
412                                 if (ControlStyleCreated)
413                                         return ((TableStyle) ControlStyle).BackImageUrl;
414                                 return String.Empty;
415                         }
416                         set {
417                                 ((TableStyle) ControlStyle).BackImageUrl = value;
418                         }
419                 }
420
421                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
422                 [BrowsableAttribute (false)]
423                 public virtual GridViewRow BottomPagerRow {
424                         get {
425                                 EnsureDataBound ();
426                                 return bottomPagerRow;
427                         }
428                 }
429         
430                 [WebCategoryAttribute ("Accessibility")]
431                 [DefaultValueAttribute ("")]
432                 [LocalizableAttribute (true)]
433                 public virtual string Caption {
434                         get {
435                                 object ob = ViewState ["Caption"];
436                                 if (ob != null) return (string) ob;
437                                 return string.Empty;
438                         }
439                         set {
440                                 ViewState ["Caption"] = value;
441                                 RequireBinding ();
442                         }
443                 }
444                 
445                 [WebCategoryAttribute ("Accessibility")]
446                 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
447                 public virtual TableCaptionAlign CaptionAlign
448                 {
449                         get {
450                                 object o = ViewState ["CaptionAlign"];
451                                 if(o != null) return (TableCaptionAlign) o;
452                                 return TableCaptionAlign.NotSet;
453                         }
454                         set {
455                                 ViewState ["CaptionAlign"] = value;
456                                 RequireBinding ();
457                         }
458                 }
459
460                 [WebCategoryAttribute ("Layout")]
461                 [DefaultValueAttribute (-1)]
462                 public virtual int CellPadding
463                 {
464                         get {
465                                 if (ControlStyleCreated)
466                                         return ((TableStyle) ControlStyle).CellPadding;
467                                 return -1;
468                         }
469                         set {
470                                 ((TableStyle) ControlStyle).CellPadding = value;
471                         }
472                 }
473
474                 [WebCategoryAttribute ("Layout")]
475                 [DefaultValueAttribute (0)]
476                 public virtual int CellSpacing
477                 {
478                         get {
479                                 if (ControlStyleCreated)
480                                         return ((TableStyle) ControlStyle).CellSpacing;
481                                 return 0;
482                         }
483                         set {
484                                 ((TableStyle) ControlStyle).CellSpacing = value;
485                         }
486                 }
487                 
488                 [EditorAttribute ("System.Web.UI.Design.WebControls.DataControlFieldTypeEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
489                 [MergablePropertyAttribute (false)]
490                 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
491                 [DefaultValueAttribute (null)]
492                 [WebCategoryAttribute ("Misc")]
493                 public virtual DataControlFieldCollection Columns {
494                         get {
495                                 if (columns == null) {
496                                         columns = new DataControlFieldCollection ();
497                                         columns.FieldsChanged += new EventHandler (OnFieldsChanged);
498                                         if (IsTrackingViewState)
499                                                 ((IStateManager)columns).TrackViewState ();
500                                 }
501                                 return columns;
502                         }
503                 }
504
505                 [DefaultValueAttribute (null)]
506                 [WebCategoryAttribute ("Data")]
507                 [TypeConverter (typeof(StringArrayConverter))]
508                 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
509                 public virtual string[] DataKeyNames
510                 {
511                         get {
512                                 if (dataKeyNames != null)
513                                         return dataKeyNames;
514                                 return emptyKeys;
515                         }
516                         set {
517                                 dataKeyNames = value;
518                                 RequireBinding ();
519                         }
520                 }
521                 
522                 [BrowsableAttribute (false)]
523                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
524                 public virtual DataKeyArray DataKeys {
525                         get {
526                                 EnsureDataBound ();
527                                 return keys;
528                         }
529                 }
530
531                 [WebCategoryAttribute ("Misc")]
532                 [DefaultValueAttribute (-1)]
533                 public virtual int EditIndex {
534                         get {
535                                 return editIndex;
536                         }
537                         set {
538                                 if (value == editIndex)
539                                         return;
540                                 editIndex = value;
541                                 RequireBinding ();
542                         }
543                 }
544         
545                 [WebCategoryAttribute ("Styles")]
546                 [PersistenceMode (PersistenceMode.InnerProperty)]
547                 [NotifyParentProperty (true)]
548                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
549                 public TableItemStyle EditRowStyle {
550                         get {
551                                 if (editRowStyle == null) {
552                                         editRowStyle = new TableItemStyle ();
553                                         if (IsTrackingViewState)
554                                                 editRowStyle.TrackViewState();
555                                 }
556                                 return editRowStyle;
557                         }
558                 }
559                 
560                 [WebCategoryAttribute ("Styles")]
561                 [PersistenceMode (PersistenceMode.InnerProperty)]
562                 [NotifyParentProperty (true)]
563                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
564                 public TableItemStyle EmptyDataRowStyle {
565                         get {
566                                 if (emptyDataRowStyle == null) {
567                                         emptyDataRowStyle = new TableItemStyle ();
568                                         if (IsTrackingViewState)
569                                                 emptyDataRowStyle.TrackViewState();
570                                 }
571                                 return emptyDataRowStyle;
572                         }
573                 }
574                 
575                 [DefaultValue (null)]
576                 [TemplateContainer (typeof(GridViewRow), BindingDirection.OneWay)]
577                 [PersistenceMode (PersistenceMode.InnerProperty)]
578                 [Browsable (false)]
579                 public virtual ITemplate EmptyDataTemplate {
580                         get { return emptyDataTemplate; }
581                         set { emptyDataTemplate = value; RequireBinding (); }
582                 }
583                 
584                 [LocalizableAttribute (true)]
585                 [WebCategoryAttribute ("Appearance")]
586                 [DefaultValueAttribute ("")]
587                 public virtual string EmptyDataText {
588                         get {
589                                 object ob = ViewState ["EmptyDataText"];
590                                 if (ob != null) return (string) ob;
591                                 return string.Empty;
592                         }
593                         set {
594                                 ViewState ["EmptyDataText"] = value;
595                                 RequireBinding ();
596                         }
597                 }
598         
599                 [WebCategoryAttribute ("Behavior")]
600                 [DefaultValueAttribute (false)]
601                 public virtual bool EnableSortingAndPagingCallbacks {
602                         get {
603                                 object ob = ViewState ["EnableSortingAndPagingCallbacks"];
604                                 if (ob != null) return (bool) ob;
605                                 return false;
606                         }
607                         set {
608                                 ViewState ["EnableSortingAndPagingCallbacks"] = value;
609                                 RequireBinding ();
610                         }
611                 }
612         
613                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
614                 [BrowsableAttribute (false)]
615                 public virtual GridViewRow FooterRow {
616                         get {
617                                 if (table != null) {
618                                         for (int index = table.Rows.Count - 1; index >= 0; index--) {
619                                                 GridViewRow row = (GridViewRow) table.Rows [index];
620                                                 switch (row.RowType) {
621                                                 case DataControlRowType.Separator:
622                                                 case DataControlRowType.Pager:
623                                                         continue;
624                                                 case DataControlRowType.Footer:
625                                                         return row;
626                                                 default:
627                                                         break;
628                                                 }
629                                         }
630                                 }
631                                 return null;
632                         }
633                 }
634         
635                 [WebCategoryAttribute ("Styles")]
636                 [PersistenceMode (PersistenceMode.InnerProperty)]
637                 [NotifyParentProperty (true)]
638                 [DefaultValue (null)]
639                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
640                 public TableItemStyle FooterStyle {
641                         get {
642                                 if (footerStyle == null) {
643                                         footerStyle = new TableItemStyle ();
644                                         if (IsTrackingViewState)
645                                                 footerStyle.TrackViewState();
646                                 }
647                                 return footerStyle;
648                         }
649                 }
650                 
651                 [WebCategoryAttribute ("Appearance")]
652                 [DefaultValueAttribute (GridLines.Both)]
653                 public virtual GridLines GridLines {
654                         get {
655                                 if (ControlStyleCreated)
656                                         return ((TableStyle) ControlStyle).GridLines;
657                                 return GridLines.Both;
658                         }
659                         set {
660                                 ((TableStyle) ControlStyle).GridLines = value;
661                         }
662                 }
663
664                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
665                 [BrowsableAttribute (false)]
666                 public virtual GridViewRow HeaderRow {
667                         get {
668                                 if (table != null) {
669                                         for (int index = 0, total = table.Rows.Count; index < total; index++) {
670                                                 GridViewRow row = (GridViewRow) table.Rows [index];
671                                                 switch (row.RowType) {
672                                                 case DataControlRowType.Separator:
673                                                 case DataControlRowType.Pager:
674                                                         continue;
675                                                 case DataControlRowType.Header:
676                                                         return row;
677                                                 default:
678                                                         break;
679                                                 }
680                                         }
681                                 }
682                                 return null;
683                         }
684                 }
685         
686                 [WebCategoryAttribute ("Styles")]
687                 [PersistenceMode (PersistenceMode.InnerProperty)]
688                 [NotifyParentProperty (true)]
689                 [DefaultValue (null)]
690                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
691                 public TableItemStyle HeaderStyle {
692                         get {
693                                 if (headerStyle == null) {
694                                         headerStyle = new TableItemStyle ();
695                                         if (IsTrackingViewState)
696                                                 headerStyle.TrackViewState();
697                                 }
698                                 return headerStyle;
699                         }
700                 }
701                 
702                 [Category ("Layout")]
703                 [DefaultValueAttribute (HorizontalAlign.NotSet)]
704                 public virtual HorizontalAlign HorizontalAlign {
705                         get {
706                                 if (ControlStyleCreated)
707                                         return ((TableStyle) ControlStyle).HorizontalAlign;
708                                 return HorizontalAlign.NotSet;
709                         }
710                         set {
711                                 ((TableStyle) ControlStyle).HorizontalAlign = value;
712                         }
713                 }
714
715                 [BrowsableAttribute (false)]
716                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
717                 public virtual int PageCount {
718                         get {
719                                 if (pageCount != 0) return pageCount;
720                                 EnsureDataBound ();
721                                 return pageCount;
722                         }
723                 }
724
725                 [WebCategoryAttribute ("Paging")]
726                 [BrowsableAttribute (true)]
727                 [DefaultValueAttribute (0)]
728                 public virtual int PageIndex {
729                         get {
730                                 return pageIndex;
731                         }
732                         set {
733                                 if (value == pageIndex)
734                                         return;
735                                 pageIndex = value;
736                                 RequireBinding ();
737                         }
738                 }
739         
740                 [DefaultValueAttribute (10)]
741                 [WebCategoryAttribute ("Paging")]
742                 public virtual int PageSize {
743                         get {
744                                 object ob = ViewState ["PageSize"];
745                                 if (ob != null) return (int) ob;
746                                 return 10;
747                         }
748                         set {
749                                 ViewState ["PageSize"] = value;
750                                 RequireBinding ();
751                         }
752                 }
753         
754                 [WebCategoryAttribute ("Paging")]
755                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
756                 [NotifyParentPropertyAttribute (true)]
757                 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
758                 public virtual PagerSettings PagerSettings {
759                         get {
760                                 if (pagerSettings == null) {
761                                         pagerSettings = new PagerSettings (this);
762                                         if (IsTrackingViewState)
763                                                 ((IStateManager)pagerSettings).TrackViewState ();
764                                 }
765                                 return pagerSettings;
766                         }
767                 }
768         
769                 [WebCategoryAttribute ("Styles")]
770                 [PersistenceMode (PersistenceMode.InnerProperty)]
771                 [NotifyParentProperty (true)]
772                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
773                 public TableItemStyle PagerStyle {
774                         get {
775                                 if (pagerStyle == null) {
776                                         pagerStyle = new TableItemStyle ();
777                                         if (IsTrackingViewState)
778                                                 pagerStyle.TrackViewState();
779                                 }
780                                 return pagerStyle;
781                         }
782                 }
783                 
784                 
785                 [DefaultValue (null)]
786                 /* DataControlPagerCell isnt specified in the docs */
787                 //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
788                 [PersistenceMode (PersistenceMode.InnerProperty)]
789                 [Browsable (false)]
790                 public virtual ITemplate PagerTemplate {
791                         get { return pagerTemplate; }
792                         set { pagerTemplate = value; RequireBinding (); }
793                 }
794                 
795                 [DefaultValueAttribute ("")]
796                 [WebCategoryAttribute ("Accessibility")]
797                 //              [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
798                 public virtual string RowHeaderColumn {
799                         get {
800                                 object ob = ViewState ["RowHeaderColumn"];
801                                 if (ob != null) return (string) ob;
802                                 return string.Empty;
803                         }
804                         set {
805                                 ViewState ["RowHeaderColumn"] = value;
806                                 RequireBinding ();
807                         }
808                 }
809                 
810                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
811                 [BrowsableAttribute (false)]
812                 public virtual GridViewRowCollection Rows {
813                         get {
814                                 EnsureDataBound ();
815                                 return rows;
816                         }
817                 }
818                 
819                 [WebCategoryAttribute ("Styles")]
820                 [PersistenceMode (PersistenceMode.InnerProperty)]
821                 [NotifyParentProperty (true)]
822                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
823                 public TableItemStyle RowStyle {
824                         get {
825                                 if (rowStyle == null) {
826                                         rowStyle = new TableItemStyle ();
827                                         if (IsTrackingViewState)
828                                                 rowStyle.TrackViewState();
829                                 }
830                                 return rowStyle;
831                         }
832                 }
833                 
834                 [BrowsableAttribute (false)]
835                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
836                 public virtual DataKey SelectedDataKey {
837                         get {
838                                 if (DataKeys == null)
839                                         throw new InvalidOperationException ("DataKeys");
840
841                                 if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
842                                         return DataKeys [selectedIndex];
843                                 } else
844                                         return null;
845                         }
846                 }
847                 
848                 [BindableAttribute (true)]
849                 [DefaultValueAttribute (-1)]
850                 public virtual int SelectedIndex {
851                         get {
852                                 return selectedIndex;
853                         }
854                         set {
855                                 if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
856                                         int oldIndex = selectedIndex;
857                                         selectedIndex = -1;
858                                         Rows [oldIndex].RowState = GetRowState (oldIndex);
859                                 }
860                                 selectedIndex = value;
861                                 if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
862                                         Rows [selectedIndex].RowState = GetRowState (selectedIndex);
863                                 }
864                         }
865                 }
866         
867                 [BrowsableAttribute (false)]
868                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
869                 public virtual GridViewRow SelectedRow {
870                         get {
871                                 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
872                                         return Rows [selectedIndex];
873                                 } else
874                                         return null;
875                         }
876                 }
877                 
878                 [WebCategoryAttribute ("Styles")]
879                 [PersistenceMode (PersistenceMode.InnerProperty)]
880                 [NotifyParentProperty (true)]
881                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
882                 public TableItemStyle SelectedRowStyle {
883                         get {
884                                 if (selectedRowStyle == null) {
885                                         selectedRowStyle = new TableItemStyle ();
886                                         if (IsTrackingViewState)
887                                                 selectedRowStyle.TrackViewState();
888                                 }
889                                 return selectedRowStyle;
890                         }
891                 }
892                 
893                 [BrowsableAttribute (false)]
894                 public object SelectedValue {
895                         get {
896                                 if (SelectedDataKey != null)
897                                         return SelectedDataKey.Value;
898                                 else
899                                         return null;
900                         }
901                 }
902                 
903                 [WebCategoryAttribute ("Appearance")]
904                 [DefaultValueAttribute (false)]
905                 public virtual bool ShowFooter {
906                         get {
907                                 object ob = ViewState ["ShowFooter"];
908                                 if (ob != null) return (bool) ob;
909                                 return false;
910                         }
911                         set {
912                                 ViewState ["ShowFooter"] = value;
913                                 RequireBinding ();
914                         }
915                 }
916         
917                 [WebCategoryAttribute ("Appearance")]
918                 [DefaultValueAttribute (true)]
919                 public virtual bool ShowHeader {
920                         get {
921                                 object ob = ViewState ["ShowHeader"];
922                                 if (ob != null) return (bool) ob;
923                                 return true;
924                         }
925                         set {
926                                 ViewState ["ShowHeader"] = value;
927                                 RequireBinding ();
928                         }
929                 }
930                 
931                 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
932                 [BrowsableAttribute (false)]
933                 [DefaultValueAttribute (SortDirection.Ascending)]
934                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
935                 public virtual SortDirection SortDirection {
936                         get { return sortDirection; }
937                         private set {
938                                 if (sortDirection == value)
939                                         return;
940                                 sortDirection = value;
941                                 RequireBinding ();
942                         }
943                 }
944                 
945                 [BrowsableAttribute (false)]
946                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
947                 public virtual string SortExpression {
948                         get {
949                                 if (sortExpression == null)
950                                         return String.Empty;
951                                 return sortExpression;
952                         }
953                         private set {
954                                 if (sortExpression == value)
955                                         return;
956                                 sortExpression = value;
957                                 RequireBinding ();
958                         }
959                 }
960                 
961                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
962                 [BrowsableAttribute (false)]
963                 public virtual GridViewRow TopPagerRow {
964                         get {
965                                 EnsureDataBound ();
966                                 return topPagerRow;
967                         }
968                 }
969         
970                 [WebCategoryAttribute ("Accessibility")]
971                 [DefaultValueAttribute (true)]
972                 public virtual bool UseAccessibleHeader {
973                         get {
974                                 object ob = ViewState ["UseAccessibleHeader"];
975                                 if (ob != null) return (bool) ob;
976                                 return true;
977                         }
978                         set {
979                                 ViewState ["UseAccessibleHeader"] = value;
980                                 RequireBinding ();
981                         }
982                 }
983         
984                 public virtual bool IsBindableType (Type type)
985                 {
986                         return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Guid);
987                 }
988                 
989                 // MSDN: The CreateDataSourceSelectArguments method is a helper method called by 
990                 // the GridView control to create the DataSourceSelectArguments object that 
991                 // contains the arguments passed to the data source. In this implementation, 
992                 // the DataSourceSelectArguments object contains the arguments for paging operations.
993                 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
994                 {
995                         DataSourceSelectArguments arg = DataSourceSelectArguments.Empty;
996                         DataSourceView view= GetData();
997                         if (AllowPaging && view.CanPage) {
998                                 arg.StartRowIndex = PageIndex * PageSize;
999                                 if (view.CanRetrieveTotalRowCount) {
1000                                         arg.RetrieveTotalRowCount = true;
1001                                         arg.MaximumRows = PageSize;
1002                                 }
1003                                 else {
1004                                         arg.MaximumRows = -1;
1005                                 }
1006                         }
1007
1008                         if (IsBoundUsingDataSourceID && !String.IsNullOrEmpty (sortExpression)) {
1009                                 if (sortDirection == SortDirection.Ascending)
1010                                         arg.SortExpression = sortExpression;
1011                                 else
1012                                         arg.SortExpression = sortExpression + " DESC";
1013                         }
1014                         
1015                         return arg;
1016                 }
1017                 
1018                 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
1019                 {
1020                         ArrayList fields = new ArrayList ();
1021                         
1022                         if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
1023                                 CommandField field = new CommandField ();
1024                                 field.ShowEditButton = AutoGenerateEditButton;
1025                                 field.ShowDeleteButton = AutoGenerateDeleteButton;
1026                                 field.ShowSelectButton = AutoGenerateSelectButton;
1027                                 fields.Add (field);
1028                         }
1029
1030                         fields.AddRange (Columns);
1031                         
1032                         if (AutoGenerateColumns) {
1033                                 if (useDataSource)
1034                                         autoFieldProperties = CreateAutoFieldProperties (dataSource);
1035         
1036                                 if (autoFieldProperties != null) {
1037                                         foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
1038                                                 fields.Add (CreateAutoGeneratedColumn (props));
1039                                 }
1040                         }
1041                         
1042                         return fields;
1043                 }
1044                 
1045                 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
1046                 {
1047                         return new AutoGeneratedField (fieldProperties);
1048                 }
1049                 
1050                 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
1051                 {
1052                         if(source == null) return null;
1053                         
1054                         PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
1055                         Type prop_type;
1056                         
1057                         ArrayList retVal = new ArrayList();
1058                         
1059                         if (props == null)
1060                         {
1061                                 object fitem = null;
1062                                 prop_type = null;
1063                                 PropertyInfo prop_item =  source.DataSource.GetType().GetProperty("Item",
1064                                                                                                   BindingFlags.Instance | BindingFlags.Static |
1065                                                                                                   BindingFlags.Public, null, null,
1066                                                                                                   new Type[] { typeof(int) }, null);
1067                                 
1068                                 if (prop_item != null) {
1069                                         prop_type = prop_item.PropertyType;
1070                                 }
1071                                 
1072                                 if (prop_type == null || prop_type == typeof(object)) {
1073                                         IEnumerator en = source.GetEnumerator();
1074                                         if (en.MoveNext())
1075                                                 fitem = en.Current;
1076                                         if (fitem != null)
1077                                                 prop_type = fitem.GetType();
1078                                 }
1079                                 
1080                                 if (fitem != null && fitem is ICustomTypeDescriptor) {
1081                                         props = TypeDescriptor.GetProperties(fitem);
1082                                 } else if (prop_type != null) {
1083                                         if (IsBindableType (prop_type)) {
1084                                                 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1085                                                 ((IStateManager)field).TrackViewState();
1086                                                 field.Name = "Item";
1087                                                 field.DataField = BoundField.ThisExpression;
1088                                                 field.Type = prop_type;
1089                                                 retVal.Add (field);
1090                                         } else {
1091                                                 props = TypeDescriptor.GetProperties (prop_type);
1092                                         }
1093                                 }
1094                         }
1095                         
1096                         if (props != null && props.Count > 0)
1097                         {
1098                                 foreach (PropertyDescriptor current in props) {
1099                                         if (IsBindableType (current.PropertyType)) {
1100                                                 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1101                                                 ((IStateManager)field).TrackViewState();
1102                                                 field.Name = current.Name;
1103                                                 field.DataField = current.Name;
1104                                                 field.IsReadOnly = current.IsReadOnly;
1105                                                 field.Type = current.PropertyType;
1106                                                 retVal.Add (field);
1107                                         }
1108                                 }
1109                         }
1110
1111                         if (retVal.Count > 0)
1112                                 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1113                         else
1114                                 return new AutoGeneratedFieldProperties [0];
1115                 }
1116                 
1117                 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1118                 {
1119                         GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1120                         OnRowCreated (new GridViewRowEventArgs (row));
1121                         return row;
1122                 }
1123                 
1124                 void RequireBinding ()
1125                 {
1126                         if (Initialized) {
1127                                 RequiresDataBinding = true;
1128                                 pageCount = -1;
1129                         }
1130                 }
1131                 
1132                 protected virtual Table CreateChildTable ()
1133                 {
1134                         return new ContainedTable (this);
1135                 }
1136         
1137                 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1138                 {
1139                         PagedDataSource dataSource;
1140
1141                         if (dataBinding) {
1142                                 DataSourceView view = GetData ();
1143                                 dataSource = new PagedDataSource ();
1144                                 dataSource.DataSource = data;
1145                                 
1146                                 if (AllowPaging) {
1147                                         dataSource.AllowPaging = true;
1148                                         dataSource.PageSize = PageSize;
1149                                         dataSource.CurrentPageIndex = PageIndex;
1150                                         if (view.CanPage) {
1151                                                 dataSource.AllowServerPaging = true;
1152                                                 if (view.CanRetrieveTotalRowCount)
1153                                                         dataSource.VirtualCount = SelectArguments.TotalRowCount;
1154                                         }
1155                                 }
1156                                 
1157                                 pageCount = dataSource.PageCount;
1158                         }
1159                         else
1160                         {
1161                                 dataSource = new PagedDataSource ();
1162                                 dataSource.DataSource = data;
1163                                 if (AllowPaging) {
1164                                         dataSource.AllowPaging = true;
1165                                         dataSource.PageSize = PageSize;
1166                                         dataSource.CurrentPageIndex = PageIndex;
1167                                 }
1168                         }
1169
1170                         bool showPager = AllowPaging && (PageCount > 1);
1171                         
1172                         Controls.Clear ();
1173                         table = CreateChildTable ();
1174                         Controls.Add (table);
1175                                 
1176                         ArrayList list = new ArrayList ();
1177                         ArrayList keyList = new ArrayList ();
1178                         
1179                         // Creates the set of fields to show
1180                         
1181                         ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1182                         DataControlField[] fields = new DataControlField [fieldCollection.Count];
1183                         fieldCollection.CopyTo (fields, 0);
1184
1185                         foreach (DataControlField field in fields) {
1186                                 field.Initialize (AllowSorting, this);
1187                                 if (EnableSortingAndPagingCallbacks)
1188                                         field.ValidateSupportsCallback ();
1189                         }
1190
1191                         // Main table creation
1192                         
1193                         if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
1194                                 topPagerRow = CreatePagerRow (fields.Length, dataSource);
1195                                 table.Rows.Add (topPagerRow);
1196                         }
1197
1198                         GridViewRow headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
1199                         table.Rows.Add (headerRow);
1200                         InitializeRow (headerRow, fields);
1201                         
1202                         foreach (object obj in dataSource) {
1203                                 DataControlRowState rstate = GetRowState (list.Count);
1204                                 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1205                                 row.DataItem = obj;
1206                                 list.Add (row);
1207                                 table.Rows.Add (row);
1208                                 InitializeRow (row, fields);
1209                                 if (dataBinding) {
1210                                         row.DataBind ();
1211                                         OnRowDataBound (new GridViewRowEventArgs (row));
1212                                         if (EditIndex == row.RowIndex)
1213                                                 oldEditValues = new DataKey (GetRowValues (row, false, true));
1214                                         keyList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1215                                 } else {
1216                                         if (EditIndex == row.RowIndex)
1217                                                 oldEditValues = new DataKey (new OrderedDictionary ());
1218                                         keyList.Add (new DataKey (new OrderedDictionary (), DataKeyNames));
1219                                 }
1220
1221                                 if (list.Count >= PageSize)
1222                                         break;
1223                         }
1224                         
1225                         if (list.Count == 0)
1226                                 table.Rows.Add (CreateEmptyrRow (fields.Length));
1227
1228                         GridViewRow footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
1229                         table.Rows.Add (footerRow);
1230                         InitializeRow (footerRow, fields);
1231
1232                         if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
1233                                 bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
1234                                 table.Rows.Add (bottomPagerRow);
1235                         }
1236
1237                         rows = new GridViewRowCollection (list);
1238                         keys = new DataKeyArray (keyList);
1239
1240                         return dataSource.DataSourceCount;
1241                 }
1242
1243                 protected override Style CreateControlStyle ()
1244                 {
1245                         TableStyle style = new TableStyle (ViewState);
1246                         style.GridLines = GridLines.Both;
1247                         style.CellSpacing = 0;
1248                         return style;
1249                 }
1250                 
1251                 DataControlRowState GetRowState (int index)
1252                 {
1253                         DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1254                         if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1255                         if (index == EditIndex) rstate |= DataControlRowState.Edit;
1256                         return rstate;
1257                 }
1258                 
1259                 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1260                 {
1261                         GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1262                         InitializePager (row, fieldCount, dataSource);
1263                         return row;
1264                 }
1265                 
1266                 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1267                 {
1268                         TableCell cell = new TableCell ();
1269                         if (columnSpan > 1)
1270                                 cell.ColumnSpan = columnSpan;
1271                         
1272                         if (pagerTemplate != null)
1273                                 pagerTemplate.InstantiateIn (cell);
1274                         else
1275                                 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1276                         
1277                         row.Cells.Add (cell);
1278                 }
1279                 
1280                 GridViewRow CreateEmptyrRow (int fieldCount)
1281                 {
1282                         GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1283                         TableCell cell = new TableCell ();
1284                         cell.ColumnSpan = fieldCount;
1285                         
1286                         if (emptyDataTemplate != null)
1287                                 emptyDataTemplate.InstantiateIn (cell);
1288                         else
1289                                 cell.Text = EmptyDataText;
1290                         
1291                         row.Cells.Add (cell);
1292                         return row;
1293                 }
1294                 
1295                 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1296                 {
1297                         DataControlCellType ctype;
1298                         bool accessibleHeader = false;
1299
1300                         switch (row.RowType) {
1301                         case DataControlRowType.Header:
1302                                 ctype = DataControlCellType.Header; 
1303                                 accessibleHeader = UseAccessibleHeader;
1304                                 break;
1305                         case DataControlRowType.Footer:
1306                                 ctype = DataControlCellType.Footer;
1307                                 break;
1308                         default:
1309                                 ctype = DataControlCellType.DataCell;
1310                                 break;
1311                         }
1312                         
1313                         for (int n=0; n<fields.Length; n++) {
1314                                 DataControlField field = fields [n];
1315                                 DataControlFieldCell cell;
1316                                 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1317                                         cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1318                                 else
1319                                         cell = new DataControlFieldCell (field);
1320                                 row.Cells.Add (cell);
1321                                 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1322                         }
1323                 }
1324                 
1325                 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1326                 {
1327                         if (cachedKeyProperties == null) {
1328                                 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1329                                 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1330                                 for (int n=0; n<DataKeyNames.Length; n++) { 
1331                                         PropertyDescriptor p = props [DataKeyNames[n]];
1332                                         if (p == null)
1333                                                 new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + row.DataItem.GetType());
1334                                         cachedKeyProperties [n] = p;
1335                                 }
1336                         }
1337                         
1338                         OrderedDictionary dic = new OrderedDictionary ();
1339                         foreach (PropertyDescriptor p in cachedKeyProperties)
1340                                 dic [p.Name] = p.GetValue (row.DataItem);
1341                         return dic;
1342                 }
1343                 
1344                 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1345                 {
1346                         OrderedDictionary dic = new OrderedDictionary ();
1347                         ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1348                         return dic;
1349                 }
1350                 
1351                 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1352                 {
1353                         foreach (TableCell cell in row.Cells) {
1354                                 DataControlFieldCell c = cell as DataControlFieldCell;
1355                                 if (c != null)
1356                                         c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1357                         }
1358                         if (!includePrimaryKey && DataKeyNames != null)
1359                                 foreach (string key in DataKeyNames)
1360                                         fieldValues.Remove (key);
1361                 }
1362                 
1363                 protected override HtmlTextWriterTag TagKey {
1364                         get {
1365                                 if (EnableSortingAndPagingCallbacks)
1366                                         return HtmlTextWriterTag.Div;
1367                                 else
1368                                         return HtmlTextWriterTag.Table;
1369                         }
1370                 }
1371                 
1372                 public sealed override void DataBind ()
1373                 {
1374                         cachedKeyProperties = null;
1375                         base.DataBind ();
1376                 }
1377                 
1378                 protected internal override void PerformDataBinding (IEnumerable data)
1379                 {
1380                         base.PerformDataBinding (data);
1381                 }
1382
1383                 protected internal virtual void PrepareControlHierarchy ()
1384                 {
1385                         if (table == null)
1386                                 return;
1387                         
1388                         table.Caption = Caption;
1389                         table.CaptionAlign = CaptionAlign;
1390                         
1391                         foreach (GridViewRow row in table.Rows) {
1392                                 switch (row.RowType) {
1393                                 case DataControlRowType.Header:
1394                                         if (headerStyle != null && !headerStyle.IsEmpty)
1395                                                 row.ControlStyle.CopyFrom(headerStyle);
1396                                         row.Visible = ShowHeader;
1397                                         break;
1398                                 case DataControlRowType.Footer:
1399                                         if (footerStyle != null && !footerStyle.IsEmpty)
1400                                                 row.ControlStyle.CopyFrom (footerStyle);
1401                                         row.Visible = ShowFooter;
1402                                         break;
1403                                 case DataControlRowType.Pager:
1404                                         if (pagerStyle != null && !pagerStyle.IsEmpty)
1405                                                 row.ControlStyle.CopyFrom (pagerStyle);
1406                                         break;
1407                                 case DataControlRowType.EmptyDataRow:
1408                                         if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1409                                                 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1410                                         break;
1411                                 case DataControlRowType.DataRow:
1412                                         if (rowStyle != null && !rowStyle.IsEmpty)
1413                                                 row.ControlStyle.CopyFrom (rowStyle);
1414                                         if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1415                                                 row.ControlStyle.CopyFrom (alternatingRowStyle);
1416                                         if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null && !selectedRowStyle.IsEmpty)
1417                                                 row.ControlStyle.CopyFrom (selectedRowStyle);
1418                                         if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1419                                                 row.ControlStyle.CopyFrom (editRowStyle);
1420                                         break;
1421                                 default:
1422                                         break;
1423                                 }
1424
1425                                 foreach (TableCell cell in row.Cells) {
1426                                         DataControlFieldCell fcell = cell as DataControlFieldCell;
1427                                         if (fcell != null) {
1428                                                 DataControlField field = fcell.ContainingField;
1429                                                 switch (row.RowType) {
1430                                                 case DataControlRowType.Header:
1431                                                         if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1432                                                                 cell.ControlStyle.CopyFrom (field.HeaderStyle);
1433                                                         break;
1434                                                 case DataControlRowType.Footer:
1435                                                         if (field.FooterStyleCreated && !field.FooterStyle.IsEmpty)
1436                                                                 cell.ControlStyle.CopyFrom (field.FooterStyle);
1437                                                         break;
1438                                                 default:
1439                                                         if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1440                                                                 foreach (Control c in cell.Controls) {
1441                                                                         WebControl wc = c as WebControl;
1442                                                                         if (wc != null)
1443                                                                                 wc.ControlStyle.MergeWith (field.ControlStyle);
1444                                                                 }
1445                                                         if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1446                                                                 cell.ControlStyle.CopyFrom (field.ItemStyle);
1447                                                         break;
1448                                                 }
1449                                         }
1450                                 }
1451                         }
1452                 }
1453                 
1454                 protected internal override void OnInit (EventArgs e)
1455                 {
1456                         Page.RegisterRequiresControlState (this);
1457                         base.OnInit (e);
1458                 }
1459                 
1460                 void OnFieldsChanged (object sender, EventArgs args)
1461                 {
1462                         RequireBinding ();
1463                 }
1464                 
1465                 protected override void OnDataPropertyChanged ()
1466                 {
1467                         base.OnDataPropertyChanged ();
1468                         RequireBinding ();
1469                 }
1470                 
1471                 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1472                 {
1473                         base.OnDataSourceViewChanged (sender, e);
1474                         RequireBinding ();
1475                 }
1476                 
1477                 protected override bool OnBubbleEvent (object source, EventArgs e)
1478                 {
1479                         GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1480                         if (args != null) {
1481                                 OnRowCommand (args);
1482                                 string param = args.CommandArgument as string;
1483                                 if (param == null || param.Length == 0) {
1484                                         GridViewRow row = args.Row;
1485                                         if (row != null)
1486                                                 param = row.RowIndex.ToString();
1487                                 }
1488                                 ProcessEvent (args.CommandName, param);
1489                         }
1490                         return base.OnBubbleEvent (source, e);
1491                 }
1492                 
1493                 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1494                 {
1495                         RaisePostBackEvent (eventArgument);
1496                 }
1497
1498                 // This is prolly obsolete
1499                 protected virtual void RaisePostBackEvent (string eventArgument)
1500                 {
1501                         int i = eventArgument.IndexOf ('$');
1502                         if (i != -1)
1503                                 ProcessEvent (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1504                         else
1505                                 ProcessEvent (eventArgument, null);
1506                 }
1507                 
1508                 void ProcessEvent (string eventName, string param)
1509                 {
1510                         switch (eventName)
1511                         {
1512                         case DataControlCommands.PageCommandName:
1513                                 int newIndex = -1;
1514                                 switch (param) {
1515                                 case DataControlCommands.FirstPageCommandArgument:
1516                                         newIndex = 0;
1517                                         break;
1518                                 case DataControlCommands.LastPageCommandArgument:
1519                                         newIndex = PageCount - 1;
1520                                         break;
1521                                 case DataControlCommands.NextPageCommandArgument:
1522                                         if (PageIndex < PageCount - 1) newIndex = PageIndex + 1;
1523                                         break;
1524                                 case DataControlCommands.PreviousPageCommandArgument:
1525                                         if (PageIndex > 0) newIndex = PageIndex - 1;
1526                                         break;
1527                                 default:
1528                                         newIndex = int.Parse (param) - 1;
1529                                         break;
1530                                 }
1531                                 ShowPage (newIndex);
1532                                 break;
1533                                         
1534                         case DataControlCommands.FirstPageCommandArgument:
1535                                 ShowPage (0);
1536                                 break;
1537
1538                         case DataControlCommands.LastPageCommandArgument:
1539                                 ShowPage (PageCount - 1);
1540                                 break;
1541                                         
1542                         case DataControlCommands.NextPageCommandArgument:
1543                                 if (PageIndex < PageCount - 1)
1544                                         ShowPage (PageIndex + 1);
1545                                 break;
1546
1547                         case DataControlCommands.PreviousPageCommandArgument:
1548                                 if (PageIndex > 0)
1549                                         ShowPage (PageIndex - 1);
1550                                 break;
1551                                         
1552                         case DataControlCommands.SelectCommandName:
1553                                 SelectRow (int.Parse (param));
1554                                 break;
1555                                         
1556                         case DataControlCommands.EditCommandName:
1557                                 EditRow (int.Parse (param));
1558                                 break;
1559                                         
1560                         case DataControlCommands.UpdateCommandName:
1561                                 UpdateRow (EditIndex, true);
1562                                 break;
1563                                         
1564                         case DataControlCommands.CancelCommandName:
1565                                 CancelEdit ();
1566                                 break;
1567                                         
1568                         case DataControlCommands.DeleteCommandName:
1569                                 DeleteRow (int.Parse (param));
1570                                 break;
1571                                         
1572                         case DataControlCommands.SortCommandName:
1573                                 Sort (param);
1574                                 break;
1575                         }
1576                 }
1577                 
1578                 void Sort (string newSortExpression)
1579                 {
1580                         SortDirection newDirection = SortDirection.Ascending;
1581                         if (sortExpression == newSortExpression && sortDirection == SortDirection.Ascending)
1582                                 newDirection = SortDirection.Descending;
1583
1584                         Sort (newSortExpression, newDirection);
1585                 }
1586                 
1587                 public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
1588                 {
1589                         GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1590                         OnSorting (args);
1591                         if (args.Cancel) return;
1592                         
1593                 if (IsBoundUsingDataSourceID) {
1594                         EditIndex = -1;
1595                         PageIndex = 0;
1596                         SortExpression = args.SortExpression;
1597                         SortDirection = args.SortDirection;
1598                 }
1599                         
1600                         OnSorted (EventArgs.Empty);
1601                 }
1602                 
1603                 void SelectRow (int index)
1604                 {
1605                         GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1606                         OnSelectedIndexChanging (args);
1607                         if (!args.Cancel) {
1608                                 SelectedIndex = args.NewSelectedIndex;
1609                                 OnSelectedIndexChanged (EventArgs.Empty);
1610                         }
1611                 }
1612                 
1613                 void ShowPage (int newIndex)
1614                 {
1615                         GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1616                         OnPageIndexChanging (args);
1617                         if (!args.Cancel) {
1618                                 EndRowEdit ();
1619                                 PageIndex = args.NewPageIndex;
1620                                 OnPageIndexChanged (EventArgs.Empty);
1621                         }
1622                 }
1623                 
1624                 void EditRow (int index)
1625                 {
1626                         GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1627                         OnRowEditing (args);
1628                         if (!args.Cancel) {
1629                                 EditIndex = args.NewEditIndex;
1630                         }
1631                 }
1632                 
1633                 void CancelEdit ()
1634                 {
1635                         GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1636                         OnRowCancelingEdit (args);
1637                         if (!args.Cancel) {
1638                                 EndRowEdit ();
1639                         }
1640                 }
1641
1642                 [MonoTODO ("Support two-way binding expressions")]
1643                 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1644                 {
1645                         if (causesValidation)
1646                                 Page.Validate ();
1647                         
1648                         if (rowIndex != EditIndex) throw new NotSupportedException ();
1649                         
1650                         currentEditOldValues = oldEditValues.Values;
1651
1652                         GridViewRow row = Rows [rowIndex];
1653                         currentEditRowKeys = DataKeys [rowIndex].Values;
1654                         currentEditNewValues = GetRowValues (row, false, false);
1655                         
1656                         GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (EditIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1657                         OnRowUpdating (args);
1658                         if (!args.Cancel) {
1659                                 DataSourceView view = GetData ();
1660                                 if (view == null) throw new HttpException ("The DataSourceView associated to data bound control was null");
1661                                 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1662                         } else
1663                                 EndRowEdit ();
1664                 }
1665
1666                 bool UpdateCallback (int recordsAffected, Exception exception)
1667                 {
1668                         GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1669                         OnRowUpdated (dargs);
1670
1671                         if (!dargs.KeepInEditMode)                              
1672                                 EndRowEdit ();
1673
1674                         return dargs.ExceptionHandled;
1675                 }
1676                 
1677                 public virtual void DeleteRow (int rowIndex)
1678                 {
1679                         GridViewRow row = Rows [rowIndex];
1680                         currentEditRowKeys = DataKeys [rowIndex].Values;
1681                         currentEditNewValues = GetRowValues (row, true, true);
1682                         
1683                         GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1684                         OnRowDeleting (args);
1685
1686                         if (!args.Cancel) {
1687                                 RequireBinding ();
1688                                 DataSourceView view = GetData ();
1689                                 if (view != null)
1690                                         view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1691                                 else {
1692                                         GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1693                                         OnRowDeleted (dargs);
1694                                 }
1695                         }
1696                 }
1697
1698                 bool DeleteCallback (int recordsAffected, Exception exception)
1699                 {
1700                         GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1701                         OnRowDeleted (dargs);
1702                         return dargs.ExceptionHandled;
1703                 }
1704                 
1705                 void EndRowEdit ()
1706                 {
1707                         EditIndex = -1;
1708                         oldEditValues = new DataKey (new OrderedDictionary ());
1709                         currentEditRowKeys = null;
1710                         currentEditOldValues = null;
1711                         currentEditNewValues = null;
1712                 }
1713
1714                 protected internal override void LoadControlState (object ob)
1715                 {
1716                         if (ob == null) return;
1717                         object[] state = (object[]) ob;
1718                         base.LoadControlState (state[0]);
1719                         pageIndex = (int) state[1];
1720                         pageCount = (int) state[2];
1721                         selectedIndex = (int) state[3];
1722                         editIndex = (int) state[4];
1723                         sortExpression = (string) state[5];
1724                         sortDirection = (SortDirection) state[6];
1725                         DataKeyNames = (string []) state [7];
1726                 }
1727                 
1728                 protected internal override object SaveControlState ()
1729                 {
1730                         if (EnableSortingAndPagingCallbacks) {
1731                                 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1732                                 Page.ClientScript.RegisterHiddenField (ClientID + "_SortExpression", SortExpression);
1733                                 Page.ClientScript.RegisterHiddenField (ClientID + "_SortDirection", ((int)SortDirection).ToString());
1734                         }
1735
1736                         object bstate = base.SaveControlState ();
1737                         return new object[] {
1738                                 bstate, pageIndex, pageCount, selectedIndex, editIndex, sortExpression, sortDirection, DataKeyNames
1739                                         };
1740                 }
1741                 
1742                 protected override void TrackViewState()
1743                 {
1744                         base.TrackViewState();
1745                         if (columns != null) ((IStateManager)columns).TrackViewState();
1746                         if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1747                         if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1748                         if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1749                         if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1750                         if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1751                         if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1752                         if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
1753                         if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1754                         if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1755                         if (keys != null) ((IStateManager)keys).TrackViewState();
1756                         if (autoFieldProperties != null) {
1757                                 foreach (IStateManager sm in autoFieldProperties)
1758                                         sm.TrackViewState ();
1759                         }
1760                 }
1761
1762                 protected override object SaveViewState()
1763                 {
1764                         object[] states = new object [14];
1765                         states[0] = base.SaveViewState();
1766                         states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
1767                         states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1768                         states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
1769                         states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1770                         states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1771                         states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1772                         states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1773                         states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
1774                         states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1775                         states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1776                         states[11] = (keys == null ? null : ((IStateManager)keys).SaveViewState());
1777                         states[12] = (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState());
1778                         
1779                         if (autoFieldProperties != null) {
1780                                 object[] data = new object [autoFieldProperties.Length];
1781                                 bool allNull = true;
1782                                 for (int n=0; n<data.Length; n++) {
1783                                         data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
1784                                         if (data [n] != null) allNull = false;
1785                                 }
1786                                 if (!allNull) states [13] = data;
1787                         }
1788
1789                         for (int i = states.Length - 1; i >= 0; i--) {
1790                                 if (states [i] != null)
1791                                         return states;
1792                         }
1793
1794                         return null;
1795                 }
1796
1797                 protected override void LoadViewState (object savedState)
1798                 {
1799                         if (savedState == null) {
1800                                 base.LoadViewState (null);
1801                                 return;
1802                         }
1803
1804                         object [] states = (object []) savedState;
1805                         
1806                         if (states[13] != null) {
1807                                 object[] data = (object[]) states [13];
1808                                 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
1809                                 for (int n=0; n<data.Length; n++) {
1810                                         IStateManager p = new AutoGeneratedFieldProperties ();
1811                                         p.TrackViewState ();
1812                                         p.LoadViewState (data [n]);
1813                                         autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
1814                                 }
1815                         }
1816
1817                         base.LoadViewState (states[0]);
1818                         EnsureChildControls ();
1819                         
1820                         if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
1821                         if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1822                         if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
1823                         if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1824                         if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1825                         if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1826                         if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1827                         if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
1828                         if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1829                         if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1830                         if (states[11] != null) ((IStateManager)DataKeys).LoadViewState (states[11]);
1831                         if (states[12] != null && oldEditValues != null) ((IStateManager)oldEditValues).LoadViewState (states[12]);
1832                 }
1833                 
1834                 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
1835                 {
1836                         RaiseCallbackEvent (eventArgs);
1837                 }
1838                 
1839                 protected virtual void RaiseCallbackEvent (string eventArgs)
1840                 {
1841                         string[] clientData = eventArgs.Split ('|');
1842                         PageIndex = int.Parse (clientData[0]);
1843                         SortExpression = HttpUtility.UrlDecode (clientData [1]);
1844                         SortDirection = (SortDirection) int.Parse (clientData [2]);
1845                         
1846                         RaisePostBackEvent (clientData[3]);
1847                         DataBind ();
1848                 }
1849                 
1850                 string ICallbackEventHandler.GetCallbackResult ()
1851                 {
1852                         return GetCallbackResult ();
1853                 }
1854
1855                 protected virtual string GetCallbackResult ()
1856                 {
1857                         PrepareControlHierarchy ();
1858                         
1859                         StringWriter sw = new StringWriter ();
1860                         sw.Write (PageIndex.ToString () + '|' + SortExpression + '|' + (int) SortDirection + '|');
1861
1862                         HtmlTextWriter writer = new HtmlTextWriter (sw);
1863                         RenderGrid (writer);
1864                         return sw.ToString ();
1865                 }
1866
1867                 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
1868                 {
1869                         return GetCallbackScript (control, argument);
1870                 }
1871                 
1872                 protected virtual string GetCallbackScript (IButtonControl control, string argument)
1873                 {
1874                         if (EnableSortingAndPagingCallbacks)
1875                                 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
1876                         else
1877                                 return null;
1878                 }
1879                 
1880                 protected override void OnPagePreLoad (object sender, EventArgs e)
1881                 {
1882                         base.OnPagePreLoad (sender, e);
1883
1884                         if (Page.IsPostBack && EnableSortingAndPagingCallbacks) {
1885                                 int page;
1886                                 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
1887                                         PageIndex = page;
1888                                 int dir;
1889                                 if (int.TryParse (Page.Request.Form [ClientID + "_SortDirection"], out dir))
1890                                         SortDirection = (SortDirection) dir;
1891                                 SortExpression = Page.Request.Form [ClientID + "_SortExpression"];
1892                         }
1893                 }
1894                 
1895                 protected internal override void OnPreRender (EventArgs e)
1896                 {
1897                         base.OnPreRender (e);
1898                         
1899                         if (EnableSortingAndPagingCallbacks)
1900                         {
1901                                 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
1902                                         string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
1903                                         Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
1904                                 }
1905                                 
1906                                 string cgrid = ClientID + "_data";
1907                                 string script = string.Format ("var {0} = new Object ();\n", cgrid);
1908                                 script += string.Format ("{0}.pageIndex = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (PageIndex));
1909                                 script += string.Format ("{0}.sortExp = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression));
1910                                 script += string.Format ("{0}.sortDir = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral ((int) SortDirection));
1911                                 script += string.Format ("{0}.uid = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (UniqueID));
1912                                 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
1913                                 
1914                                 // Make sure the basic script infrastructure is rendered
1915                                 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
1916                                 Page.ClientScript.GetPostBackClientHyperlink (this, "");
1917                         }
1918                 }
1919
1920                 protected internal override void Render (HtmlTextWriter writer)
1921                 {
1922                         PrepareControlHierarchy ();
1923
1924                         if (EnableSortingAndPagingCallbacks)
1925                                 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID);
1926                         writer.RenderBeginTag (HtmlTextWriterTag.Div);
1927
1928                         RenderGrid (writer);
1929
1930                         writer.RenderEndTag ();
1931                 }
1932                 
1933                 void RenderGrid (HtmlTextWriter writer)
1934                 {
1935                         if (table == null)
1936                                 return;
1937
1938                         table.Render (writer);
1939                 }
1940
1941                 [MonoTODO]
1942                 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1943                 {
1944                         PostBackOptions pbo = new PostBackOptions (this, control.CommandName + "$" + control.CommandArgument);
1945                         return pbo;
1946                 }
1947         }
1948 }
1949
1950 #endif