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