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