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