Fix problems with overlong directory names: phase #1
[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                 ArrayList _dataKeyArrayList;
78                 DataKeyArray keys;
79                 DataKey oldEditValues;
80                 AutoGeneratedFieldProperties[] autoFieldProperties;
81                 string [] dataKeyNames = null;
82                 readonly string[] emptyKeys = new string[0];
83                 
84                 private static readonly object PageIndexChangedEvent = new object();
85                 private static readonly object PageIndexChangingEvent = new object();
86                 private static readonly object RowCancelingEditEvent = new object();
87                 private static readonly object RowCommandEvent = new object();
88                 private static readonly object RowCreatedEvent = new object();
89                 private static readonly object RowDataBoundEvent = new object();
90                 private static readonly object RowDeletedEvent = new object();
91                 private static readonly object RowDeletingEvent = new object();
92                 private static readonly object RowEditingEvent = new object();
93                 private static readonly object RowUpdatedEvent = new object();
94                 private static readonly object RowUpdatingEvent = new object();
95                 private static readonly object SelectedIndexChangedEvent = new object();
96                 private static readonly object SelectedIndexChangingEvent = new object();
97                 private static readonly object SortedEvent = new object();
98                 private static readonly object SortingEvent = new object();
99                 
100                 // Control state
101                 int pageIndex;
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                 ArrayList DataKeyArrayList {
523                         get {
524                                 if (_dataKeyArrayList == null) {
525                                         _dataKeyArrayList = new ArrayList ();
526                                 }
527                                 return _dataKeyArrayList;
528                         }
529                 }
530                 
531                 [BrowsableAttribute (false)]
532                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
533                 public virtual DataKeyArray DataKeys {
534                         get {
535                                 if (keys == null) {
536                                         keys = new DataKeyArray (DataKeyArrayList);
537                                         if (IsTrackingViewState)
538                                                 ((IStateManager) keys).TrackViewState ();
539                                 }
540                                 return keys;
541                         }
542                 }
543
544                 DataKey OldEditValues {
545                         get {
546                                 if (oldEditValues == null) {
547                                         oldEditValues = new DataKey (new OrderedDictionary ());
548                                 }
549                                 return oldEditValues;
550                         }
551                 }
552
553                 [WebCategoryAttribute ("Misc")]
554                 [DefaultValueAttribute (-1)]
555                 public virtual int EditIndex {
556                         get {
557                                 return editIndex;
558                         }
559                         set {
560                                 if (value == editIndex)
561                                         return;
562                                 editIndex = value;
563                                 RequireBinding ();
564                         }
565                 }
566         
567                 [WebCategoryAttribute ("Styles")]
568                 [PersistenceMode (PersistenceMode.InnerProperty)]
569                 [NotifyParentProperty (true)]
570                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
571                 public TableItemStyle EditRowStyle {
572                         get {
573                                 if (editRowStyle == null) {
574                                         editRowStyle = new TableItemStyle ();
575                                         if (IsTrackingViewState)
576                                                 editRowStyle.TrackViewState();
577                                 }
578                                 return editRowStyle;
579                         }
580                 }
581                 
582                 [WebCategoryAttribute ("Styles")]
583                 [PersistenceMode (PersistenceMode.InnerProperty)]
584                 [NotifyParentProperty (true)]
585                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
586                 public TableItemStyle EmptyDataRowStyle {
587                         get {
588                                 if (emptyDataRowStyle == null) {
589                                         emptyDataRowStyle = new TableItemStyle ();
590                                         if (IsTrackingViewState)
591                                                 emptyDataRowStyle.TrackViewState();
592                                 }
593                                 return emptyDataRowStyle;
594                         }
595                 }
596                 
597                 [DefaultValue (null)]
598                 [TemplateContainer (typeof(GridViewRow), BindingDirection.OneWay)]
599                 [PersistenceMode (PersistenceMode.InnerProperty)]
600                 [Browsable (false)]
601                 public virtual ITemplate EmptyDataTemplate {
602                         get { return emptyDataTemplate; }
603                         set { emptyDataTemplate = value; RequireBinding (); }
604                 }
605                 
606                 [LocalizableAttribute (true)]
607                 [WebCategoryAttribute ("Appearance")]
608                 [DefaultValueAttribute ("")]
609                 public virtual string EmptyDataText {
610                         get {
611                                 object ob = ViewState ["EmptyDataText"];
612                                 if (ob != null) return (string) ob;
613                                 return string.Empty;
614                         }
615                         set {
616                                 ViewState ["EmptyDataText"] = value;
617                                 RequireBinding ();
618                         }
619                 }
620         
621                 [WebCategoryAttribute ("Behavior")]
622                 [DefaultValueAttribute (false)]
623                 public virtual bool EnableSortingAndPagingCallbacks {
624                         get {
625                                 object ob = ViewState ["EnableSortingAndPagingCallbacks"];
626                                 if (ob != null) return (bool) ob;
627                                 return false;
628                         }
629                         set {
630                                 ViewState ["EnableSortingAndPagingCallbacks"] = value;
631                                 RequireBinding ();
632                         }
633                 }
634         
635                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
636                 [BrowsableAttribute (false)]
637                 public virtual GridViewRow FooterRow {
638                         get {
639                                 if (table != null) {
640                                         for (int index = table.Rows.Count - 1; index >= 0; index--) {
641                                                 GridViewRow row = (GridViewRow) table.Rows [index];
642                                                 switch (row.RowType) {
643                                                 case DataControlRowType.Separator:
644                                                 case DataControlRowType.Pager:
645                                                         continue;
646                                                 case DataControlRowType.Footer:
647                                                         return row;
648                                                 default:
649                                                         break;
650                                                 }
651                                         }
652                                 }
653                                 return null;
654                         }
655                 }
656         
657                 [WebCategoryAttribute ("Styles")]
658                 [PersistenceMode (PersistenceMode.InnerProperty)]
659                 [NotifyParentProperty (true)]
660                 [DefaultValue (null)]
661                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
662                 public TableItemStyle FooterStyle {
663                         get {
664                                 if (footerStyle == null) {
665                                         footerStyle = new TableItemStyle ();
666                                         if (IsTrackingViewState)
667                                                 footerStyle.TrackViewState();
668                                 }
669                                 return footerStyle;
670                         }
671                 }
672                 
673                 [WebCategoryAttribute ("Appearance")]
674                 [DefaultValueAttribute (GridLines.Both)]
675                 public virtual GridLines GridLines {
676                         get {
677                                 if (ControlStyleCreated)
678                                         return ((TableStyle) ControlStyle).GridLines;
679                                 return GridLines.Both;
680                         }
681                         set {
682                                 ((TableStyle) ControlStyle).GridLines = value;
683                         }
684                 }
685
686                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
687                 [BrowsableAttribute (false)]
688                 public virtual GridViewRow HeaderRow {
689                         get {
690                                 if (table != null) {
691                                         for (int index = 0, total = table.Rows.Count; index < total; index++) {
692                                                 GridViewRow row = (GridViewRow) table.Rows [index];
693                                                 switch (row.RowType) {
694                                                 case DataControlRowType.Separator:
695                                                 case DataControlRowType.Pager:
696                                                         continue;
697                                                 case DataControlRowType.Header:
698                                                         return row;
699                                                 default:
700                                                         break;
701                                                 }
702                                         }
703                                 }
704                                 return null;
705                         }
706                 }
707         
708                 [WebCategoryAttribute ("Styles")]
709                 [PersistenceMode (PersistenceMode.InnerProperty)]
710                 [NotifyParentProperty (true)]
711                 [DefaultValue (null)]
712                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
713                 public TableItemStyle HeaderStyle {
714                         get {
715                                 if (headerStyle == null) {
716                                         headerStyle = new TableItemStyle ();
717                                         if (IsTrackingViewState)
718                                                 headerStyle.TrackViewState();
719                                 }
720                                 return headerStyle;
721                         }
722                 }
723                 
724                 [Category ("Layout")]
725                 [DefaultValueAttribute (HorizontalAlign.NotSet)]
726                 public virtual HorizontalAlign HorizontalAlign {
727                         get {
728                                 if (ControlStyleCreated)
729                                         return ((TableStyle) ControlStyle).HorizontalAlign;
730                                 return HorizontalAlign.NotSet;
731                         }
732                         set {
733                                 ((TableStyle) ControlStyle).HorizontalAlign = value;
734                         }
735                 }
736
737                 [BrowsableAttribute (false)]
738                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
739                 public virtual int PageCount {
740                         get {
741                                 return ViewState.GetInt ("PageCount", 0);
742                         }
743                         private set {
744                                 ViewState ["PageCount"] = value;
745                         }
746                 }
747
748                 [WebCategoryAttribute ("Paging")]
749                 [BrowsableAttribute (true)]
750                 [DefaultValueAttribute (0)]
751                 public virtual int PageIndex {
752                         get {
753                                 return pageIndex;
754                         }
755                         set {
756                                 if (value == pageIndex)
757                                         return;
758                                 pageIndex = value;
759                                 RequireBinding ();
760                         }
761                 }
762         
763                 [DefaultValueAttribute (10)]
764                 [WebCategoryAttribute ("Paging")]
765                 public virtual int PageSize {
766                         get {
767                                 object ob = ViewState ["PageSize"];
768                                 if (ob != null) return (int) ob;
769                                 return 10;
770                         }
771                         set {
772                                 ViewState ["PageSize"] = value;
773                                 RequireBinding ();
774                         }
775                 }
776         
777                 [WebCategoryAttribute ("Paging")]
778                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
779                 [NotifyParentPropertyAttribute (true)]
780                 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
781                 public virtual PagerSettings PagerSettings {
782                         get {
783                                 if (pagerSettings == null) {
784                                         pagerSettings = new PagerSettings (this);
785                                         if (IsTrackingViewState)
786                                                 ((IStateManager)pagerSettings).TrackViewState ();
787                                 }
788                                 return pagerSettings;
789                         }
790                 }
791         
792                 [WebCategoryAttribute ("Styles")]
793                 [PersistenceMode (PersistenceMode.InnerProperty)]
794                 [NotifyParentProperty (true)]
795                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
796                 public TableItemStyle PagerStyle {
797                         get {
798                                 if (pagerStyle == null) {
799                                         pagerStyle = new TableItemStyle ();
800                                         if (IsTrackingViewState)
801                                                 pagerStyle.TrackViewState();
802                                 }
803                                 return pagerStyle;
804                         }
805                 }
806                 
807                 
808                 [DefaultValue (null)]
809                 /* DataControlPagerCell isnt specified in the docs */
810                 //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
811                 [PersistenceMode (PersistenceMode.InnerProperty)]
812                 [Browsable (false)]
813                 public virtual ITemplate PagerTemplate {
814                         get { return pagerTemplate; }
815                         set { pagerTemplate = value; RequireBinding (); }
816                 }
817                 
818                 [DefaultValueAttribute ("")]
819                 [WebCategoryAttribute ("Accessibility")]
820                 //              [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
821                 public virtual string RowHeaderColumn {
822                         get {
823                                 object ob = ViewState ["RowHeaderColumn"];
824                                 if (ob != null) return (string) ob;
825                                 return string.Empty;
826                         }
827                         set {
828                                 ViewState ["RowHeaderColumn"] = value;
829                                 RequireBinding ();
830                         }
831                 }
832                 
833                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
834                 [BrowsableAttribute (false)]
835                 public virtual GridViewRowCollection Rows {
836                         get {
837                                 EnsureDataBound ();
838                                 return rows;
839                         }
840                 }
841                 
842                 [WebCategoryAttribute ("Styles")]
843                 [PersistenceMode (PersistenceMode.InnerProperty)]
844                 [NotifyParentProperty (true)]
845                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
846                 public TableItemStyle RowStyle {
847                         get {
848                                 if (rowStyle == null) {
849                                         rowStyle = new TableItemStyle ();
850                                         if (IsTrackingViewState)
851                                                 rowStyle.TrackViewState();
852                                 }
853                                 return rowStyle;
854                         }
855                 }
856                 
857                 [BrowsableAttribute (false)]
858                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
859                 public virtual DataKey SelectedDataKey {
860                         get {
861                                 if (keys == null)
862                                         throw new InvalidOperationException ("DataKeys");
863
864                                 if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
865                                         return DataKeys [selectedIndex];
866                                 } else
867                                         return null;
868                         }
869                 }
870                 
871                 [BindableAttribute (true)]
872                 [DefaultValueAttribute (-1)]
873                 public virtual int SelectedIndex {
874                         get {
875                                 return selectedIndex;
876                         }
877                         set {
878                                 if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
879                                         int oldIndex = selectedIndex;
880                                         selectedIndex = -1;
881                                         Rows [oldIndex].RowState = GetRowState (oldIndex);
882                                 }
883                                 selectedIndex = value;
884                                 if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
885                                         Rows [selectedIndex].RowState = GetRowState (selectedIndex);
886                                 }
887                         }
888                 }
889         
890                 [BrowsableAttribute (false)]
891                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
892                 public virtual GridViewRow SelectedRow {
893                         get {
894                                 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
895                                         return Rows [selectedIndex];
896                                 } else
897                                         return null;
898                         }
899                 }
900                 
901                 [WebCategoryAttribute ("Styles")]
902                 [PersistenceMode (PersistenceMode.InnerProperty)]
903                 [NotifyParentProperty (true)]
904                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
905                 public TableItemStyle SelectedRowStyle {
906                         get {
907                                 if (selectedRowStyle == null) {
908                                         selectedRowStyle = new TableItemStyle ();
909                                         if (IsTrackingViewState)
910                                                 selectedRowStyle.TrackViewState();
911                                 }
912                                 return selectedRowStyle;
913                         }
914                 }
915                 
916                 [BrowsableAttribute (false)]
917                 public object SelectedValue {
918                         get {
919                                 if (SelectedDataKey != null)
920                                         return SelectedDataKey.Value;
921                                 else
922                                         return null;
923                         }
924                 }
925                 
926                 [WebCategoryAttribute ("Appearance")]
927                 [DefaultValueAttribute (false)]
928                 public virtual bool ShowFooter {
929                         get {
930                                 object ob = ViewState ["ShowFooter"];
931                                 if (ob != null) return (bool) ob;
932                                 return false;
933                         }
934                         set {
935                                 ViewState ["ShowFooter"] = value;
936                                 RequireBinding ();
937                         }
938                 }
939         
940                 [WebCategoryAttribute ("Appearance")]
941                 [DefaultValueAttribute (true)]
942                 public virtual bool ShowHeader {
943                         get {
944                                 object ob = ViewState ["ShowHeader"];
945                                 if (ob != null) return (bool) ob;
946                                 return true;
947                         }
948                         set {
949                                 ViewState ["ShowHeader"] = value;
950                                 RequireBinding ();
951                         }
952                 }
953                 
954                 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
955                 [BrowsableAttribute (false)]
956                 [DefaultValueAttribute (SortDirection.Ascending)]
957                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
958                 public virtual SortDirection SortDirection {
959                         get { return sortDirection; }
960                         private set {
961                                 if (sortDirection == value)
962                                         return;
963                                 sortDirection = value;
964                                 RequireBinding ();
965                         }
966                 }
967                 
968                 [BrowsableAttribute (false)]
969                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
970                 public virtual string SortExpression {
971                         get {
972                                 if (sortExpression == null)
973                                         return String.Empty;
974                                 return sortExpression;
975                         }
976                         private set {
977                                 if (sortExpression == value)
978                                         return;
979                                 sortExpression = value;
980                                 RequireBinding ();
981                         }
982                 }
983                 
984                 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
985                 [BrowsableAttribute (false)]
986                 public virtual GridViewRow TopPagerRow {
987                         get {
988                                 EnsureDataBound ();
989                                 return topPagerRow;
990                         }
991                 }
992         
993                 [WebCategoryAttribute ("Accessibility")]
994                 [DefaultValueAttribute (true)]
995                 public virtual bool UseAccessibleHeader {
996                         get {
997                                 object ob = ViewState ["UseAccessibleHeader"];
998                                 if (ob != null) return (bool) ob;
999                                 return true;
1000                         }
1001                         set {
1002                                 ViewState ["UseAccessibleHeader"] = value;
1003                                 RequireBinding ();
1004                         }
1005                 }
1006         
1007                 public virtual bool IsBindableType (Type type)
1008                 {
1009                         return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Guid);
1010                 }
1011                 
1012                 // MSDN: The CreateDataSourceSelectArguments method is a helper method called by 
1013                 // the GridView control to create the DataSourceSelectArguments object that 
1014                 // contains the arguments passed to the data source. In this implementation, 
1015                 // the DataSourceSelectArguments object contains the arguments for paging operations.
1016                 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
1017                 {
1018                         DataSourceSelectArguments arg = DataSourceSelectArguments.Empty;
1019                         DataSourceView view= GetData();
1020                         if (AllowPaging && view.CanPage) {
1021                                 arg.StartRowIndex = PageIndex * PageSize;
1022                                 if (view.CanRetrieveTotalRowCount) {
1023                                         arg.RetrieveTotalRowCount = true;
1024                                         arg.MaximumRows = PageSize;
1025                                 }
1026                                 else {
1027                                         arg.MaximumRows = -1;
1028                                 }
1029                         }
1030
1031                         if (IsBoundUsingDataSourceID && !String.IsNullOrEmpty (sortExpression)) {
1032                                 if (sortDirection == SortDirection.Ascending)
1033                                         arg.SortExpression = sortExpression;
1034                                 else
1035                                         arg.SortExpression = sortExpression + " DESC";
1036                         }
1037                         
1038                         return arg;
1039                 }
1040                 
1041                 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
1042                 {
1043                         ArrayList fields = new ArrayList ();
1044                         
1045                         if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
1046                                 CommandField field = new CommandField ();
1047                                 field.ShowEditButton = AutoGenerateEditButton;
1048                                 field.ShowDeleteButton = AutoGenerateDeleteButton;
1049                                 field.ShowSelectButton = AutoGenerateSelectButton;
1050                                 fields.Add (field);
1051                         }
1052
1053                         fields.AddRange (Columns);
1054                         
1055                         if (AutoGenerateColumns) {
1056                                 if (useDataSource)
1057                                         autoFieldProperties = CreateAutoFieldProperties (dataSource);
1058         
1059                                 if (autoFieldProperties != null) {
1060                                         foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
1061                                                 fields.Add (CreateAutoGeneratedColumn (props));
1062                                 }
1063                         }
1064                         
1065                         return fields;
1066                 }
1067                 
1068                 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
1069                 {
1070                         return new AutoGeneratedField (fieldProperties);
1071                 }
1072                 
1073                 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
1074                 {
1075                         if(source == null) return null;
1076                         
1077                         PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
1078                         Type prop_type;
1079                         
1080                         ArrayList retVal = new ArrayList();
1081                         
1082                         if (props == null)
1083                         {
1084                                 object fitem = null;
1085                                 prop_type = null;
1086                                 PropertyInfo prop_item =  source.DataSource.GetType().GetProperty("Item",
1087                                                                                                   BindingFlags.Instance | BindingFlags.Static |
1088                                                                                                   BindingFlags.Public, null, null,
1089                                                                                                   new Type[] { typeof(int) }, null);
1090                                 
1091                                 if (prop_item != null) {
1092                                         prop_type = prop_item.PropertyType;
1093                                 }
1094                                 
1095                                 if (prop_type == null || prop_type == typeof(object)) {
1096                                         IEnumerator en = source.GetEnumerator();
1097                                         if (en.MoveNext())
1098                                                 fitem = en.Current;
1099                                         if (fitem != null)
1100                                                 prop_type = fitem.GetType();
1101                                 }
1102                                 
1103                                 if (fitem != null && fitem is ICustomTypeDescriptor) {
1104                                         props = TypeDescriptor.GetProperties(fitem);
1105                                 } else if (prop_type != null) {
1106                                         if (IsBindableType (prop_type)) {
1107                                                 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1108                                                 ((IStateManager)field).TrackViewState();
1109                                                 field.Name = "Item";
1110                                                 field.DataField = BoundField.ThisExpression;
1111                                                 field.Type = prop_type;
1112                                                 retVal.Add (field);
1113                                         } else {
1114                                                 props = TypeDescriptor.GetProperties (prop_type);
1115                                         }
1116                                 }
1117                         }
1118                         
1119                         if (props != null && props.Count > 0)
1120                         {
1121                                 foreach (PropertyDescriptor current in props) {
1122                                         if (IsBindableType (current.PropertyType)) {
1123                                                 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1124                                                 ((IStateManager)field).TrackViewState();
1125                                                 field.Name = current.Name;
1126                                                 field.DataField = current.Name;
1127                                                 field.IsReadOnly = current.IsReadOnly;
1128                                                 field.Type = current.PropertyType;
1129                                                 retVal.Add (field);
1130                                         }
1131                                 }
1132                         }
1133
1134                         if (retVal.Count > 0)
1135                                 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1136                         else
1137                                 return new AutoGeneratedFieldProperties [0];
1138                 }
1139                 
1140                 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1141                 {
1142                         GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1143                         return row;
1144                 }
1145                 
1146                 void RequireBinding ()
1147                 {
1148                         if (Initialized) {
1149                                 RequiresDataBinding = true;
1150                         }
1151                 }
1152                 
1153                 protected virtual Table CreateChildTable ()
1154                 {
1155                         return new ContainedTable (this);
1156                 }
1157         
1158                 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1159                 {
1160                         PagedDataSource dataSource;
1161
1162                         if (dataBinding) {
1163                                 DataSourceView view = GetData ();
1164                                 dataSource = new PagedDataSource ();
1165                                 dataSource.DataSource = data;
1166                                 
1167                                 if (AllowPaging) {
1168                                         dataSource.AllowPaging = true;
1169                                         dataSource.PageSize = PageSize;
1170                                         dataSource.CurrentPageIndex = PageIndex;
1171                                         if (view.CanPage) {
1172                                                 dataSource.AllowServerPaging = true;
1173                                                 if (SelectArguments.RetrieveTotalRowCount)
1174                                                         dataSource.VirtualCount = SelectArguments.TotalRowCount;
1175                                         }
1176                                 }
1177                                 
1178                                 PageCount = dataSource.PageCount;
1179                         }
1180                         else
1181                         {
1182                                 dataSource = new PagedDataSource ();
1183                                 dataSource.DataSource = data;
1184                                 if (AllowPaging) {
1185                                         dataSource.AllowPaging = true;
1186                                         dataSource.PageSize = PageSize;
1187                                         dataSource.CurrentPageIndex = PageIndex;
1188                                 }
1189                         }
1190
1191                         bool showPager = AllowPaging && (PageCount > 1);
1192                         
1193                         Controls.Clear ();
1194                         table = CreateChildTable ();
1195                         Controls.Add (table);
1196                                 
1197                         ArrayList list = new ArrayList ();
1198                         
1199                         // Creates the set of fields to show
1200                         
1201                         ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1202                         DataControlField[] fields = new DataControlField [fieldCollection.Count];
1203                         fieldCollection.CopyTo (fields, 0);
1204
1205                         foreach (DataControlField field in fields) {
1206                                 field.Initialize (AllowSorting, this);
1207                                 if (EnableSortingAndPagingCallbacks)
1208                                         field.ValidateSupportsCallback ();
1209                         }
1210
1211                         // Main table creation
1212                         
1213                         if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
1214                                 topPagerRow = CreatePagerRow (fields.Length, dataSource);
1215                                 table.Rows.Add (topPagerRow);
1216                                 OnRowCreated (new GridViewRowEventArgs (topPagerRow));
1217                         }
1218
1219                         GridViewRow headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
1220                         table.Rows.Add (headerRow);
1221                         InitializeRow (headerRow, fields);
1222                         OnRowCreated (new GridViewRowEventArgs (headerRow));
1223                         
1224                         foreach (object obj in dataSource) {
1225                                 DataControlRowState rstate = GetRowState (list.Count);
1226                                 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1227                                 row.DataItem = obj;
1228                                 list.Add (row);
1229                                 table.Rows.Add (row);
1230                                 InitializeRow (row, fields);
1231                                 OnRowCreated (new GridViewRowEventArgs (row));
1232                                 if (dataBinding) {
1233                                         row.DataBind ();
1234                                         OnRowDataBound (new GridViewRowEventArgs (row));
1235                                         if (EditIndex == row.RowIndex)
1236                                                 oldEditValues = new DataKey (GetRowValues (row, false, true));
1237                                         DataKeyArrayList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1238                                 } 
1239
1240                                 if (list.Count >= PageSize)
1241                                         break;
1242                         }
1243
1244                         if (list.Count == 0) {
1245                                 GridViewRow emptyRow = CreateEmptyrRow (fields.Length);
1246                                 table.Rows.Add (emptyRow);
1247                                 OnRowCreated (new GridViewRowEventArgs (emptyRow));
1248                         }
1249
1250                         GridViewRow footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
1251                         table.Rows.Add (footerRow);
1252                         InitializeRow (footerRow, fields);
1253                         OnRowCreated (new GridViewRowEventArgs (footerRow));
1254
1255                         if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
1256                                 bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
1257                                 table.Rows.Add (bottomPagerRow);
1258                                 OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
1259                         }
1260
1261                         rows = new GridViewRowCollection (list);
1262
1263                         return dataSource.DataSourceCount;
1264                 }
1265
1266                 protected override Style CreateControlStyle ()
1267                 {
1268                         TableStyle style = new TableStyle (ViewState);
1269                         style.GridLines = GridLines.Both;
1270                         style.CellSpacing = 0;
1271                         return style;
1272                 }
1273                 
1274                 DataControlRowState GetRowState (int index)
1275                 {
1276                         DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1277                         if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1278                         if (index == EditIndex) rstate |= DataControlRowState.Edit;
1279                         return rstate;
1280                 }
1281                 
1282                 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1283                 {
1284                         GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1285                         InitializePager (row, fieldCount, dataSource);
1286                         return row;
1287                 }
1288                 
1289                 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1290                 {
1291                         TableCell cell = new TableCell ();
1292                         if (columnSpan > 1)
1293                                 cell.ColumnSpan = columnSpan;
1294                         
1295                         if (pagerTemplate != null)
1296                                 pagerTemplate.InstantiateIn (cell);
1297                         else
1298                                 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1299                         
1300                         row.Cells.Add (cell);
1301                 }
1302                 
1303                 GridViewRow CreateEmptyrRow (int fieldCount)
1304                 {
1305                         GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1306                         TableCell cell = new TableCell ();
1307                         cell.ColumnSpan = fieldCount;
1308                         
1309                         if (emptyDataTemplate != null)
1310                                 emptyDataTemplate.InstantiateIn (cell);
1311                         else
1312                                 cell.Text = EmptyDataText;
1313                         
1314                         row.Cells.Add (cell);
1315                         return row;
1316                 }
1317                 
1318                 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1319                 {
1320                         DataControlCellType ctype;
1321                         bool accessibleHeader = false;
1322
1323                         switch (row.RowType) {
1324                         case DataControlRowType.Header:
1325                                 ctype = DataControlCellType.Header; 
1326                                 accessibleHeader = UseAccessibleHeader;
1327                                 break;
1328                         case DataControlRowType.Footer:
1329                                 ctype = DataControlCellType.Footer;
1330                                 break;
1331                         default:
1332                                 ctype = DataControlCellType.DataCell;
1333                                 break;
1334                         }
1335                         
1336                         for (int n=0; n<fields.Length; n++) {
1337                                 DataControlField field = fields [n];
1338                                 DataControlFieldCell cell;
1339                                 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1340                                         cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1341                                 else
1342                                         cell = new DataControlFieldCell (field);
1343                                 row.Cells.Add (cell);
1344                                 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1345                         }
1346                 }
1347                 
1348                 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1349                 {
1350                         if (cachedKeyProperties == null) {
1351                                 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1352                                 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1353                                 for (int n=0; n<DataKeyNames.Length; n++) { 
1354                                         PropertyDescriptor p = props [DataKeyNames[n]];
1355                                         if (p == null)
1356                                                 new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + row.DataItem.GetType());
1357                                         cachedKeyProperties [n] = p;
1358                                 }
1359                         }
1360                         
1361                         OrderedDictionary dic = new OrderedDictionary ();
1362                         foreach (PropertyDescriptor p in cachedKeyProperties)
1363                                 dic [p.Name] = p.GetValue (row.DataItem);
1364                         return dic;
1365                 }
1366                 
1367                 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1368                 {
1369                         OrderedDictionary dic = new OrderedDictionary ();
1370                         ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1371                         return dic;
1372                 }
1373                 
1374                 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1375                 {
1376                         foreach (TableCell cell in row.Cells) {
1377                                 DataControlFieldCell c = cell as DataControlFieldCell;
1378                                 if (c != null)
1379                                         c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1380                         }
1381                         if (!includePrimaryKey && DataKeyNames != null)
1382                                 foreach (string key in DataKeyNames)
1383                                         fieldValues.Remove (key);
1384                 }
1385                 
1386                 protected override HtmlTextWriterTag TagKey {
1387                         get {
1388                                 if (EnableSortingAndPagingCallbacks)
1389                                         return HtmlTextWriterTag.Div;
1390                                 else
1391                                         return HtmlTextWriterTag.Table;
1392                         }
1393                 }
1394                 
1395                 public sealed override void DataBind ()
1396                 {
1397                         DataKeyArrayList.Clear ();
1398                         cachedKeyProperties = null;
1399                         base.DataBind ();
1400
1401                         keys = new DataKeyArray (DataKeyArrayList);
1402                 }
1403                 
1404                 protected internal override void PerformDataBinding (IEnumerable data)
1405                 {
1406                         base.PerformDataBinding (data);
1407                 }
1408
1409                 protected internal virtual void PrepareControlHierarchy ()
1410                 {
1411                         if (table == null)
1412                                 return;
1413                         
1414                         table.Caption = Caption;
1415                         table.CaptionAlign = CaptionAlign;
1416                         
1417                         foreach (GridViewRow row in table.Rows) {
1418                                 switch (row.RowType) {
1419                                 case DataControlRowType.Header:
1420                                         if (headerStyle != null && !headerStyle.IsEmpty)
1421                                                 row.ControlStyle.CopyFrom(headerStyle);
1422                                         row.Visible = ShowHeader;
1423                                         break;
1424                                 case DataControlRowType.Footer:
1425                                         if (footerStyle != null && !footerStyle.IsEmpty)
1426                                                 row.ControlStyle.CopyFrom (footerStyle);
1427                                         row.Visible = ShowFooter;
1428                                         break;
1429                                 case DataControlRowType.Pager:
1430                                         if (pagerStyle != null && !pagerStyle.IsEmpty)
1431                                                 row.ControlStyle.CopyFrom (pagerStyle);
1432                                         break;
1433                                 case DataControlRowType.EmptyDataRow:
1434                                         if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1435                                                 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1436                                         break;
1437                                 case DataControlRowType.DataRow:
1438                                         if (rowStyle != null && !rowStyle.IsEmpty)
1439                                                 row.ControlStyle.CopyFrom (rowStyle);
1440                                         if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1441                                                 row.ControlStyle.CopyFrom (alternatingRowStyle);
1442                                         if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null && !selectedRowStyle.IsEmpty)
1443                                                 row.ControlStyle.CopyFrom (selectedRowStyle);
1444                                         if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1445                                                 row.ControlStyle.CopyFrom (editRowStyle);
1446                                         break;
1447                                 default:
1448                                         break;
1449                                 }
1450
1451                                 foreach (TableCell cell in row.Cells) {
1452                                         DataControlFieldCell fcell = cell as DataControlFieldCell;
1453                                         if (fcell != null) {
1454                                                 DataControlField field = fcell.ContainingField;
1455                                                 switch (row.RowType) {
1456                                                 case DataControlRowType.Header:
1457                                                         if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1458                                                                 cell.ControlStyle.CopyFrom (field.HeaderStyle);
1459                                                         break;
1460                                                 case DataControlRowType.Footer:
1461                                                         if (field.FooterStyleCreated && !field.FooterStyle.IsEmpty)
1462                                                                 cell.ControlStyle.CopyFrom (field.FooterStyle);
1463                                                         break;
1464                                                 default:
1465                                                         if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1466                                                                 foreach (Control c in cell.Controls) {
1467                                                                         WebControl wc = c as WebControl;
1468                                                                         if (wc != null)
1469                                                                                 wc.ControlStyle.MergeWith (field.ControlStyle);
1470                                                                 }
1471                                                         if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1472                                                                 cell.ControlStyle.CopyFrom (field.ItemStyle);
1473                                                         break;
1474                                                 }
1475                                         }
1476                                 }
1477                         }
1478                 }
1479                 
1480                 protected internal override void OnInit (EventArgs e)
1481                 {
1482                         Page.RegisterRequiresControlState (this);
1483                         base.OnInit (e);
1484                 }
1485                 
1486                 void OnFieldsChanged (object sender, EventArgs args)
1487                 {
1488                         RequireBinding ();
1489                 }
1490                 
1491                 protected override void OnDataPropertyChanged ()
1492                 {
1493                         base.OnDataPropertyChanged ();
1494                         RequireBinding ();
1495                 }
1496                 
1497                 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1498                 {
1499                         base.OnDataSourceViewChanged (sender, e);
1500                         RequireBinding ();
1501                 }
1502                 
1503                 protected override bool OnBubbleEvent (object source, EventArgs e)
1504                 {
1505                         GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1506                         if (args != null) {
1507                                 OnRowCommand (args);
1508                                 string param = args.CommandArgument as string;
1509                                 if (param == null || param.Length == 0) {
1510                                         GridViewRow row = args.Row;
1511                                         if (row != null)
1512                                                 param = row.RowIndex.ToString();
1513                                 }
1514                                 ProcessEvent (args.CommandName, param);
1515                                 return true;
1516                         }
1517                         return base.OnBubbleEvent (source, e);
1518                 }
1519                 
1520                 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1521                 {
1522                         RaisePostBackEvent (eventArgument);
1523                 }
1524
1525                 // This is prolly obsolete
1526                 protected virtual void RaisePostBackEvent (string eventArgument)
1527                 {
1528                         int i = eventArgument.IndexOf ('$');
1529                         if (i != -1)
1530                                 ProcessEvent (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1531                         else
1532                                 ProcessEvent (eventArgument, null);
1533                 }
1534                 
1535                 void ProcessEvent (string eventName, string param)
1536                 {
1537                         switch (eventName)
1538                         {
1539                         case DataControlCommands.PageCommandName:
1540                                 int newIndex = -1;
1541                                 switch (param) {
1542                                 case DataControlCommands.FirstPageCommandArgument:
1543                                         newIndex = 0;
1544                                         break;
1545                                 case DataControlCommands.LastPageCommandArgument:
1546                                         newIndex = PageCount - 1;
1547                                         break;
1548                                 case DataControlCommands.NextPageCommandArgument:
1549                                         newIndex = PageIndex + 1;
1550                                         break;
1551                                 case DataControlCommands.PreviousPageCommandArgument:
1552                                         newIndex = PageIndex - 1;
1553                                         break;
1554                                 default:
1555                                         int paramIndex = 0;
1556                                         int.TryParse (param, out paramIndex);
1557                                         newIndex = paramIndex - 1;
1558                                         break;
1559                                 }
1560                                 ShowPage (newIndex);
1561                                 break;
1562                                         
1563                         case DataControlCommands.FirstPageCommandArgument:
1564                                 ShowPage (0);
1565                                 break;
1566
1567                         case DataControlCommands.LastPageCommandArgument:
1568                                 ShowPage (PageCount - 1);
1569                                 break;
1570                                         
1571                         case DataControlCommands.NextPageCommandArgument:
1572                                 if (PageIndex < PageCount - 1)
1573                                         ShowPage (PageIndex + 1);
1574                                 break;
1575
1576                         case DataControlCommands.PreviousPageCommandArgument:
1577                                 if (PageIndex > 0)
1578                                         ShowPage (PageIndex - 1);
1579                                 break;
1580                                         
1581                         case DataControlCommands.SelectCommandName:
1582                                 SelectRow (int.Parse (param));
1583                                 break;
1584                                         
1585                         case DataControlCommands.EditCommandName:
1586                                 EditRow (int.Parse (param));
1587                                 break;
1588                                         
1589                         case DataControlCommands.UpdateCommandName:
1590                                 UpdateRow (EditIndex, true);
1591                                 break;
1592                                         
1593                         case DataControlCommands.CancelCommandName:
1594                                 CancelEdit ();
1595                                 break;
1596                                         
1597                         case DataControlCommands.DeleteCommandName:
1598                                 DeleteRow (int.Parse (param));
1599                                 break;
1600                                         
1601                         case DataControlCommands.SortCommandName:
1602                                 Sort (param);
1603                                 break;
1604                         }
1605                 }
1606                 
1607                 void Sort (string newSortExpression)
1608                 {
1609                         SortDirection newDirection = SortDirection.Ascending;
1610                         if (sortExpression == newSortExpression && sortDirection == SortDirection.Ascending)
1611                                 newDirection = SortDirection.Descending;
1612
1613                         Sort (newSortExpression, newDirection);
1614                 }
1615                 
1616                 public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
1617                 {
1618                         GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1619                         OnSorting (args);
1620                         if (args.Cancel) return;
1621                         
1622                 if (IsBoundUsingDataSourceID) {
1623                         EditIndex = -1;
1624                         PageIndex = 0;
1625                         SortExpression = args.SortExpression;
1626                         SortDirection = args.SortDirection;
1627                 }
1628                         
1629                         OnSorted (EventArgs.Empty);
1630                 }
1631                 
1632                 void SelectRow (int index)
1633                 {
1634                         GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1635                         OnSelectedIndexChanging (args);
1636                         if (!args.Cancel) {
1637                                 SelectedIndex = args.NewSelectedIndex;
1638                                 OnSelectedIndexChanged (EventArgs.Empty);
1639                         }
1640                 }
1641                 
1642                 void ShowPage (int newIndex)
1643                 {
1644                         GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1645                         OnPageIndexChanging (args);
1646                         if (!args.Cancel) {
1647                                 EndRowEdit ();
1648                                 PageIndex = args.NewPageIndex;
1649                                 OnPageIndexChanged (EventArgs.Empty);
1650                         }
1651                 }
1652                 
1653                 void EditRow (int index)
1654                 {
1655                         GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1656                         OnRowEditing (args);
1657                         if (!args.Cancel) {
1658                                 EditIndex = args.NewEditIndex;
1659                         }
1660                 }
1661                 
1662                 void CancelEdit ()
1663                 {
1664                         GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1665                         OnRowCancelingEdit (args);
1666                         if (!args.Cancel) {
1667                                 EndRowEdit ();
1668                         }
1669                 }
1670
1671                 [MonoTODO ("Support two-way binding expressions")]
1672                 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1673                 {
1674                         if (causesValidation && Page != null)
1675                                 Page.Validate ();
1676                         
1677                         if (rowIndex != EditIndex) throw new NotSupportedException ();
1678
1679                         currentEditOldValues = OldEditValues.Values;
1680
1681                         GridViewRow row = Rows [rowIndex];
1682                         currentEditRowKeys = DataKeys [rowIndex].Values;
1683                         currentEditNewValues = GetRowValues (row, false, false);
1684                         
1685                         GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (EditIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1686                         OnRowUpdating (args);
1687                         if (!args.Cancel) {
1688                                 DataSourceView view = GetData ();
1689                                 if (view == null)
1690                                         throw new HttpException ("The DataSourceView associated to data bound control was null");
1691                                 if(view.CanUpdate)
1692                                         view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1693                         } else
1694                                 EndRowEdit ();
1695                 }
1696
1697                 bool UpdateCallback (int recordsAffected, Exception exception)
1698                 {
1699                         GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1700                         OnRowUpdated (dargs);
1701
1702                         if (!dargs.KeepInEditMode)                              
1703                                 EndRowEdit ();
1704
1705                         return dargs.ExceptionHandled;
1706                 }
1707                 
1708                 public virtual void DeleteRow (int rowIndex)
1709                 {
1710                         GridViewRow row = Rows [rowIndex];
1711                         currentEditRowKeys = DataKeys [rowIndex].Values;
1712                         currentEditNewValues = GetRowValues (row, true, true);
1713                         
1714                         GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1715                         OnRowDeleting (args);
1716
1717                         if (!args.Cancel) {
1718                                 RequireBinding ();
1719                                 DataSourceView view = GetData ();
1720                                 if (view != null && view.CanDelete)
1721                                         view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1722                                 else {
1723                                         GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1724                                         OnRowDeleted (dargs);
1725                                 }
1726                         }
1727                 }
1728
1729                 bool DeleteCallback (int recordsAffected, Exception exception)
1730                 {
1731                         GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1732                         OnRowDeleted (dargs);
1733                         return dargs.ExceptionHandled;
1734                 }
1735                 
1736                 void EndRowEdit ()
1737                 {
1738                         EditIndex = -1;
1739                         oldEditValues = new DataKey (new OrderedDictionary ());
1740                         currentEditRowKeys = null;
1741                         currentEditOldValues = null;
1742                         currentEditNewValues = null;
1743                 }
1744
1745                 protected internal override void LoadControlState (object ob)
1746                 {
1747                         if (ob == null) return;
1748                         object[] state = (object[]) ob;
1749                         base.LoadControlState (state[0]);
1750                         pageIndex = (int) state[1];
1751                         selectedIndex = (int) state[2];
1752                         editIndex = (int) state[3];
1753                         sortExpression = (string) state[4];
1754                         sortDirection = (SortDirection) state[5];
1755                         DataKeyNames = (string []) state [6];
1756                         if (state [7] != null)
1757                                 LoadDataKeyArrayState ((object []) state [7]);
1758                         if (state [8] != null)
1759                                 ((IStateManager) OldEditValues).LoadViewState (state [8]);
1760                 }
1761                 
1762                 protected internal override object SaveControlState ()
1763                 {
1764                         if (EnableSortingAndPagingCallbacks) {
1765                                 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1766                                 Page.ClientScript.RegisterHiddenField (ClientID + "_SortExpression", SortExpression);
1767                                 Page.ClientScript.RegisterHiddenField (ClientID + "_SortDirection", ((int)SortDirection).ToString());
1768                         }
1769
1770                         object bstate = base.SaveControlState ();
1771                         return new object [] {
1772                                 bstate, 
1773                                 pageIndex, 
1774                                 selectedIndex, 
1775                                 editIndex, 
1776                                 sortExpression, 
1777                                 sortDirection, 
1778                                 DataKeyNames,
1779                                 SaveDataKeyArrayState (),
1780                                 (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState ())
1781                                         };
1782                 }
1783
1784                 object [] SaveDataKeyArrayState ()
1785                 {
1786                         if (keys == null)
1787                                 return null;
1788
1789                         object [] state = new object [keys.Count];
1790                         for (int i = 0; i < keys.Count; i++) {
1791                                 state [i] = ((IStateManager) keys [i]).SaveViewState ();
1792                         }
1793                         return state;
1794                 }
1795
1796                 void LoadDataKeyArrayState (object [] state)
1797                 {
1798                         for (int i = 0; i < state.Length; i++) {
1799                                 DataKey dataKey = new DataKey (new OrderedDictionary (DataKeyNames.Length), DataKeyNames);
1800                                 ((IStateManager) dataKey).LoadViewState (state [i]);
1801                                 DataKeyArrayList.Add (dataKey);
1802                         }
1803                         keys = new DataKeyArray (DataKeyArrayList);
1804                 }
1805
1806                 protected override void TrackViewState()
1807                 {
1808                         base.TrackViewState();
1809                         if (columns != null) ((IStateManager)columns).TrackViewState();
1810                         if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1811                         if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1812                         if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1813                         if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1814                         if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1815                         if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1816                         if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
1817                         if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1818                         if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1819                         if (keys != null) ((IStateManager)keys).TrackViewState();
1820                         if (autoFieldProperties != null) {
1821                                 foreach (IStateManager sm in autoFieldProperties)
1822                                         sm.TrackViewState ();
1823                         }
1824                 }
1825
1826                 protected override object SaveViewState()
1827                 {
1828                         object[] states = new object [12];
1829                         states[0] = base.SaveViewState();
1830                         states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
1831                         states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1832                         states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
1833                         states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1834                         states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1835                         states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1836                         states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1837                         states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
1838                         states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1839                         states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1840                         
1841                         if (autoFieldProperties != null) {
1842                                 object[] data = new object [autoFieldProperties.Length];
1843                                 bool allNull = true;
1844                                 for (int n=0; n<data.Length; n++) {
1845                                         data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
1846                                         if (data [n] != null) allNull = false;
1847                                 }
1848                                 if (!allNull) states [11] = data;
1849                         }
1850
1851                         for (int i = states.Length - 1; i >= 0; i--) {
1852                                 if (states [i] != null)
1853                                         return states;
1854                         }
1855
1856                         return null;
1857                 }
1858
1859                 protected override void LoadViewState (object savedState)
1860                 {
1861                         if (savedState == null) {
1862                                 base.LoadViewState (null);
1863                                 return;
1864                         }
1865
1866                         object [] states = (object []) savedState;
1867                         
1868                         if (states[11] != null) {
1869                                 object[] data = (object[]) states [11];
1870                                 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
1871                                 for (int n=0; n<data.Length; n++) {
1872                                         IStateManager p = new AutoGeneratedFieldProperties ();
1873                                         p.TrackViewState ();
1874                                         p.LoadViewState (data [n]);
1875                                         autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
1876                                 }
1877                         }
1878
1879                         base.LoadViewState (states[0]);
1880                         
1881                         if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
1882                         if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1883                         if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
1884                         if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1885                         if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1886                         if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1887                         if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1888                         if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
1889                         if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1890                         if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1891                 }
1892                 
1893                 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
1894                 {
1895                         RaiseCallbackEvent (eventArgs);
1896                 }
1897                 
1898                 protected virtual void RaiseCallbackEvent (string eventArgs)
1899                 {
1900                         string[] clientData = eventArgs.Split ('|');
1901                         PageIndex = int.Parse (clientData[0]);
1902                         SortExpression = HttpUtility.UrlDecode (clientData [1]);
1903                         SortDirection = (SortDirection) int.Parse (clientData [2]);
1904                         
1905                         RaisePostBackEvent (clientData[3]);
1906                         DataBind ();
1907                 }
1908                 
1909                 string ICallbackEventHandler.GetCallbackResult ()
1910                 {
1911                         return GetCallbackResult ();
1912                 }
1913
1914                 protected virtual string GetCallbackResult ()
1915                 {
1916                         PrepareControlHierarchy ();
1917                         
1918                         StringWriter sw = new StringWriter ();
1919                         sw.Write (PageIndex.ToString () + '|' + SortExpression + '|' + (int) SortDirection + '|');
1920
1921                         HtmlTextWriter writer = new HtmlTextWriter (sw);
1922                         RenderGrid (writer);
1923                         return sw.ToString ();
1924                 }
1925
1926                 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
1927                 {
1928                         return GetCallbackScript (control, argument);
1929                 }
1930                 
1931                 protected virtual string GetCallbackScript (IButtonControl control, string argument)
1932                 {
1933                         if (EnableSortingAndPagingCallbacks)
1934                                 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
1935                         else
1936                                 return null;
1937                 }
1938                 
1939                 protected override void OnPagePreLoad (object sender, EventArgs e)
1940                 {
1941                         base.OnPagePreLoad (sender, e);
1942
1943                         if (Page.IsPostBack && EnableSortingAndPagingCallbacks) {
1944                                 int page;
1945                                 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
1946                                         PageIndex = page;
1947                                 int dir;
1948                                 if (int.TryParse (Page.Request.Form [ClientID + "_SortDirection"], out dir))
1949                                         SortDirection = (SortDirection) dir;
1950                                 SortExpression = Page.Request.Form [ClientID + "_SortExpression"];
1951                         }
1952                 }
1953                 
1954                 protected internal override void OnPreRender (EventArgs e)
1955                 {
1956                         base.OnPreRender (e);
1957                         
1958                         if (EnableSortingAndPagingCallbacks)
1959                         {
1960                                 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
1961                                         string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
1962                                         Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
1963                                 }
1964                                 
1965                                 string cgrid = ClientID + "_data";
1966                                 string script = string.Format ("var {0} = new Object ();\n", cgrid);
1967                                 script += string.Format ("{0}.pageIndex = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (PageIndex));
1968                                 script += string.Format ("{0}.sortExp = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression));
1969                                 script += string.Format ("{0}.sortDir = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral ((int) SortDirection));
1970                                 script += string.Format ("{0}.uid = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (UniqueID));
1971                                 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
1972                                 
1973                                 // Make sure the basic script infrastructure is rendered
1974                                 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
1975                                 Page.ClientScript.GetPostBackClientHyperlink (this, "");
1976                         }
1977                 }
1978
1979                 protected internal override void Render (HtmlTextWriter writer)
1980                 {
1981                         PrepareControlHierarchy ();
1982
1983                         if (EnableSortingAndPagingCallbacks)
1984                                 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID);
1985                         writer.RenderBeginTag (HtmlTextWriterTag.Div);
1986
1987                         RenderGrid (writer);
1988
1989                         writer.RenderEndTag ();
1990                 }
1991                 
1992                 void RenderGrid (HtmlTextWriter writer)
1993                 {
1994                         if (table == null)
1995                                 return;
1996
1997                         table.Render (writer);
1998                 }
1999
2000                 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
2001                 {
2002                         if (control == null)
2003                                 throw new ArgumentNullException ("control");
2004                         
2005                         if (control.CausesValidation)
2006                                 throw new InvalidOperationException ("A button that causes validation in GridView '" + ID + "' is attempting to use the container GridView as the post back target.  The button should either turn off validation or use itself as the post back container.");
2007                         
2008                         PostBackOptions options = new PostBackOptions (this);
2009                         options.Argument = control.CommandName + "$" + control.CommandArgument;
2010                         options.RequiresJavaScriptProtocol = true;
2011
2012                         return options;
2013                 }
2014         }
2015 }
2016
2017 #endif