2 // System.Web.UI.WebControls.GridView.cs
5 // Lluis Sanchez Gual (lluis@novell.com)
7 // (C) 2005 Novell, Inc (http://www.novell.com)
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.ComponentModel;
36 using System.Security.Permissions;
39 using System.Reflection;
41 namespace System.Web.UI.WebControls
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
52 GridViewRowCollection rows;
53 GridViewRow bottomPagerRow;
54 GridViewRow topPagerRow;
56 IOrderedDictionary currentEditRowKeys;
57 IOrderedDictionary currentEditNewValues;
58 IOrderedDictionary currentEditOldValues;
60 ITemplate pagerTemplate;
61 ITemplate emptyDataTemplate;
63 PropertyDescriptor[] cachedKeyProperties;
66 DataControlFieldCollection columns;
67 PagerSettings pagerSettings;
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;
79 DataKey oldEditValues;
80 AutoGeneratedFieldProperties[] autoFieldProperties;
81 string [] dataKeyNames = null;
82 readonly string[] emptyKeys = new string[0];
83 IEnumerator _dataEnumerator;
85 private static readonly object PageIndexChangedEvent = new object();
86 private static readonly object PageIndexChangingEvent = new object();
87 private static readonly object RowCancelingEditEvent = new object();
88 private static readonly object RowCommandEvent = new object();
89 private static readonly object RowCreatedEvent = new object();
90 private static readonly object RowDataBoundEvent = new object();
91 private static readonly object RowDeletedEvent = new object();
92 private static readonly object RowDeletingEvent = new object();
93 private static readonly object RowEditingEvent = new object();
94 private static readonly object RowUpdatedEvent = new object();
95 private static readonly object RowUpdatingEvent = new object();
96 private static readonly object SelectedIndexChangedEvent = new object();
97 private static readonly object SelectedIndexChangingEvent = new object();
98 private static readonly object SortedEvent = new object();
99 private static readonly object SortingEvent = new object();
103 int selectedIndex = -1;
105 SortDirection sortDirection = SortDirection.Ascending;
106 string sortExpression;
112 public event EventHandler PageIndexChanged {
113 add { Events.AddHandler (PageIndexChangedEvent, value); }
114 remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
117 public event GridViewPageEventHandler PageIndexChanging {
118 add { Events.AddHandler (PageIndexChangingEvent, value); }
119 remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
122 public event GridViewCancelEditEventHandler RowCancelingEdit {
123 add { Events.AddHandler (RowCancelingEditEvent, value); }
124 remove { Events.RemoveHandler (RowCancelingEditEvent, value); }
127 public event GridViewCommandEventHandler RowCommand {
128 add { Events.AddHandler (RowCommandEvent, value); }
129 remove { Events.RemoveHandler (RowCommandEvent, value); }
132 public event GridViewRowEventHandler RowCreated {
133 add { Events.AddHandler (RowCreatedEvent, value); }
134 remove { Events.RemoveHandler (RowCreatedEvent, value); }
137 public event GridViewRowEventHandler RowDataBound {
138 add { Events.AddHandler (RowDataBoundEvent, value); }
139 remove { Events.RemoveHandler (RowDataBoundEvent, value); }
142 public event GridViewDeletedEventHandler RowDeleted {
143 add { Events.AddHandler (RowDeletedEvent, value); }
144 remove { Events.RemoveHandler (RowDeletedEvent, value); }
147 public event GridViewDeleteEventHandler RowDeleting {
148 add { Events.AddHandler (RowDeletingEvent, value); }
149 remove { Events.RemoveHandler (RowDeletingEvent, value); }
152 public event GridViewEditEventHandler RowEditing {
153 add { Events.AddHandler (RowEditingEvent, value); }
154 remove { Events.RemoveHandler (RowEditingEvent, value); }
157 public event GridViewUpdatedEventHandler RowUpdated {
158 add { Events.AddHandler (RowUpdatedEvent, value); }
159 remove { Events.RemoveHandler (RowUpdatedEvent, value); }
162 public event GridViewUpdateEventHandler RowUpdating {
163 add { Events.AddHandler (RowUpdatingEvent, value); }
164 remove { Events.RemoveHandler (RowUpdatingEvent, value); }
167 public event EventHandler SelectedIndexChanged {
168 add { Events.AddHandler (SelectedIndexChangedEvent, value); }
169 remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
172 public event GridViewSelectEventHandler SelectedIndexChanging {
173 add { Events.AddHandler (SelectedIndexChangingEvent, value); }
174 remove { Events.RemoveHandler (SelectedIndexChangingEvent, value); }
177 public event EventHandler Sorted {
178 add { Events.AddHandler (SortedEvent, value); }
179 remove { Events.RemoveHandler (SortedEvent, value); }
182 public event GridViewSortEventHandler Sorting {
183 add { Events.AddHandler (SortingEvent, value); }
184 remove { Events.RemoveHandler (SortingEvent, value); }
187 protected virtual void OnPageIndexChanged (EventArgs e)
189 if (Events != null) {
190 EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
191 if (eh != null) eh (this, e);
195 protected virtual void OnPageIndexChanging (GridViewPageEventArgs e)
197 if (Events != null) {
198 GridViewPageEventHandler eh = (GridViewPageEventHandler) Events [PageIndexChangingEvent];
204 if (!IsBoundUsingDataSourceID)
205 throw new HttpException (String.Format ("The GridView '{0}' fired event PageIndexChanging which wasn't handled.", ID));
208 protected virtual void OnRowCancelingEdit (GridViewCancelEditEventArgs e)
210 if (Events != null) {
211 GridViewCancelEditEventHandler eh = (GridViewCancelEditEventHandler) Events [RowCancelingEditEvent];
217 if (!IsBoundUsingDataSourceID)
218 throw new HttpException (String.Format ("The GridView '{0}' fired event RowCancelingEdit which wasn't handled.", ID));
221 protected virtual void OnRowCommand (GridViewCommandEventArgs e)
223 if (Events != null) {
224 GridViewCommandEventHandler eh = (GridViewCommandEventHandler) Events [RowCommandEvent];
225 if (eh != null) eh (this, e);
229 protected virtual void OnRowCreated (GridViewRowEventArgs e)
231 if (Events != null) {
232 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowCreatedEvent];
233 if (eh != null) eh (this, e);
237 protected virtual void OnRowDataBound (GridViewRowEventArgs e)
239 if (Events != null) {
240 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowDataBoundEvent];
241 if (eh != null) eh (this, e);
245 protected virtual void OnRowDeleted (GridViewDeletedEventArgs e)
247 if (Events != null) {
248 GridViewDeletedEventHandler eh = (GridViewDeletedEventHandler) Events [RowDeletedEvent];
249 if (eh != null) eh (this, e);
253 protected virtual void OnRowDeleting (GridViewDeleteEventArgs e)
255 if (Events != null) {
256 GridViewDeleteEventHandler eh = (GridViewDeleteEventHandler) Events [RowDeletingEvent];
262 if (!IsBoundUsingDataSourceID)
263 throw new HttpException (String.Format ("The GridView '{0}' fired event RowDeleting which wasn't handled.", ID));
266 protected virtual void OnRowEditing (GridViewEditEventArgs e)
268 if (Events != null) {
269 GridViewEditEventHandler eh = (GridViewEditEventHandler) Events [RowEditingEvent];
275 if (!IsBoundUsingDataSourceID)
276 throw new HttpException (String.Format ("The GridView '{0}' fired event RowEditing which wasn't handled.", ID));
279 protected virtual void OnRowUpdated (GridViewUpdatedEventArgs e)
281 if (Events != null) {
282 GridViewUpdatedEventHandler eh = (GridViewUpdatedEventHandler) Events [RowUpdatedEvent];
283 if (eh != null) eh (this, e);
287 protected virtual void OnRowUpdating (GridViewUpdateEventArgs e)
289 if (Events != null) {
290 GridViewUpdateEventHandler eh = (GridViewUpdateEventHandler) Events [RowUpdatingEvent];
296 if (!IsBoundUsingDataSourceID)
297 throw new HttpException (String.Format ("The GridView '{0}' fired event RowUpdating which wasn't handled.", ID));
300 protected virtual void OnSelectedIndexChanged (EventArgs e)
302 if (Events != null) {
303 EventHandler eh = (EventHandler) Events [SelectedIndexChangedEvent];
304 if (eh != null) eh (this, e);
308 protected virtual void OnSelectedIndexChanging (GridViewSelectEventArgs e)
310 if (Events != null) {
311 GridViewSelectEventHandler eh = (GridViewSelectEventHandler) Events [SelectedIndexChangingEvent];
312 if (eh != null) eh (this, e);
316 protected virtual void OnSorted (EventArgs e)
318 if (Events != null) {
319 EventHandler eh = (EventHandler) Events [SortedEvent];
320 if (eh != null) eh (this, e);
324 protected virtual void OnSorting (GridViewSortEventArgs e)
326 if (Events != null) {
327 GridViewSortEventHandler eh = (GridViewSortEventHandler) Events [SortingEvent];
333 if (!IsBoundUsingDataSourceID)
334 throw new HttpException (String.Format ("The GridView '{0}' fired event Sorting which wasn't handled.", ID));
338 [WebCategoryAttribute ("Paging")]
339 [DefaultValueAttribute (false)]
340 public virtual bool AllowPaging {
342 object ob = ViewState ["AllowPaging"];
343 if (ob != null) return (bool) ob;
347 if (value == AllowPaging)
349 ViewState ["AllowPaging"] = value;
354 [WebCategoryAttribute ("Behavior")]
355 [DefaultValueAttribute (false)]
356 public virtual bool AllowSorting {
358 object ob = ViewState ["AllowSorting"];
359 if (ob != null) return (bool) ob;
363 if (value == AllowSorting)
365 ViewState ["AllowSorting"] = value;
370 [WebCategoryAttribute ("Styles")]
371 [PersistenceMode (PersistenceMode.InnerProperty)]
372 [NotifyParentProperty (true)]
373 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
374 public TableItemStyle AlternatingRowStyle {
376 if (alternatingRowStyle == null) {
377 alternatingRowStyle = new TableItemStyle ();
378 if (IsTrackingViewState)
379 alternatingRowStyle.TrackViewState();
381 return alternatingRowStyle;
385 [WebCategoryAttribute ("Behavior")]
386 [DefaultValueAttribute (false)]
387 public virtual bool AutoGenerateEditButton {
389 object ob = ViewState ["AutoGenerateEditButton"];
390 if (ob != null) return (bool) ob;
394 if (value == AutoGenerateEditButton)
396 ViewState ["AutoGenerateEditButton"] = value;
401 [WebCategoryAttribute ("Behavior")]
402 [DefaultValueAttribute (false)]
403 public virtual bool AutoGenerateDeleteButton {
405 object ob = ViewState ["AutoGenerateDeleteButton"];
406 if (ob != null) return (bool) ob;
410 if (value == AutoGenerateDeleteButton)
412 ViewState ["AutoGenerateDeleteButton"] = value;
417 [WebCategoryAttribute ("Behavior")]
418 [DefaultValueAttribute (false)]
419 public virtual bool AutoGenerateSelectButton {
421 object ob = ViewState ["AutoGenerateSelectButton"];
422 if (ob != null) return (bool) ob;
426 if (value == AutoGenerateSelectButton)
428 ViewState ["AutoGenerateSelectButton"] = value;
433 [WebCategoryAttribute ("Behavior")]
434 [DefaultValueAttribute (true)]
435 public virtual bool AutoGenerateColumns {
437 object ob = ViewState ["AutoGenerateColumns"];
438 if (ob != null) return (bool) ob;
442 if (value == AutoGenerateColumns)
444 ViewState ["AutoGenerateColumns"] = value;
449 [UrlPropertyAttribute]
450 [WebCategoryAttribute ("Appearance")]
451 [DefaultValueAttribute ("")]
452 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
453 public virtual string BackImageUrl {
455 if (ControlStyleCreated)
456 return ((TableStyle) ControlStyle).BackImageUrl;
460 ((TableStyle) ControlStyle).BackImageUrl = value;
464 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
465 [BrowsableAttribute (false)]
466 public virtual GridViewRow BottomPagerRow {
469 return bottomPagerRow;
473 [WebCategoryAttribute ("Accessibility")]
474 [DefaultValueAttribute ("")]
475 [LocalizableAttribute (true)]
476 public virtual string Caption {
478 object ob = ViewState ["Caption"];
479 if (ob != null) return (string) ob;
483 ViewState ["Caption"] = value;
487 [WebCategoryAttribute ("Accessibility")]
488 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
489 public virtual TableCaptionAlign CaptionAlign
492 object o = ViewState ["CaptionAlign"];
493 if(o != null) return (TableCaptionAlign) o;
494 return TableCaptionAlign.NotSet;
497 ViewState ["CaptionAlign"] = value;
501 [WebCategoryAttribute ("Layout")]
502 [DefaultValueAttribute (-1)]
503 public virtual int CellPadding
506 if (ControlStyleCreated)
507 return ((TableStyle) ControlStyle).CellPadding;
511 ((TableStyle) ControlStyle).CellPadding = value;
515 [WebCategoryAttribute ("Layout")]
516 [DefaultValueAttribute (0)]
517 public virtual int CellSpacing
520 if (ControlStyleCreated)
521 return ((TableStyle) ControlStyle).CellSpacing;
525 ((TableStyle) ControlStyle).CellSpacing = value;
529 [EditorAttribute ("System.Web.UI.Design.WebControls.DataControlFieldTypeEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
530 [MergablePropertyAttribute (false)]
531 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
532 [DefaultValueAttribute (null)]
533 [WebCategoryAttribute ("Misc")]
534 public virtual DataControlFieldCollection Columns {
536 if (columns == null) {
537 columns = new DataControlFieldCollection ();
538 columns.FieldsChanged += new EventHandler (OnFieldsChanged);
539 if (IsTrackingViewState)
540 ((IStateManager)columns).TrackViewState ();
546 [DefaultValueAttribute (null)]
547 [WebCategoryAttribute ("Data")]
548 [TypeConverter (typeof(StringArrayConverter))]
549 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
550 public virtual string[] DataKeyNames
553 if (dataKeyNames != null)
558 dataKeyNames = value;
563 ArrayList DataKeyArrayList {
565 if (_dataKeyArrayList == null) {
566 _dataKeyArrayList = new ArrayList ();
568 return _dataKeyArrayList;
572 [BrowsableAttribute (false)]
573 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
574 public virtual DataKeyArray DataKeys {
577 keys = new DataKeyArray (DataKeyArrayList);
578 if (IsTrackingViewState)
579 ((IStateManager) keys).TrackViewState ();
585 DataKey OldEditValues {
587 if (oldEditValues == null) {
588 oldEditValues = new DataKey (new OrderedDictionary ());
590 return oldEditValues;
594 [WebCategoryAttribute ("Misc")]
595 [DefaultValueAttribute (-1)]
596 public virtual int EditIndex {
601 if (value == editIndex)
608 [WebCategoryAttribute ("Styles")]
609 [PersistenceMode (PersistenceMode.InnerProperty)]
610 [NotifyParentProperty (true)]
611 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
612 public TableItemStyle EditRowStyle {
614 if (editRowStyle == null) {
615 editRowStyle = new TableItemStyle ();
616 if (IsTrackingViewState)
617 editRowStyle.TrackViewState();
623 [WebCategoryAttribute ("Styles")]
624 [PersistenceMode (PersistenceMode.InnerProperty)]
625 [NotifyParentProperty (true)]
626 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
627 public TableItemStyle EmptyDataRowStyle {
629 if (emptyDataRowStyle == null) {
630 emptyDataRowStyle = new TableItemStyle ();
631 if (IsTrackingViewState)
632 emptyDataRowStyle.TrackViewState();
634 return emptyDataRowStyle;
638 [DefaultValue (null)]
639 [TemplateContainer (typeof(GridViewRow), BindingDirection.OneWay)]
640 [PersistenceMode (PersistenceMode.InnerProperty)]
642 public virtual ITemplate EmptyDataTemplate {
643 get { return emptyDataTemplate; }
644 set { emptyDataTemplate = value; }
647 [LocalizableAttribute (true)]
648 [WebCategoryAttribute ("Appearance")]
649 [DefaultValueAttribute ("")]
650 public virtual string EmptyDataText {
652 object ob = ViewState ["EmptyDataText"];
653 if (ob != null) return (string) ob;
657 if (value == EmptyDataText)
659 ViewState ["EmptyDataText"] = value;
664 [WebCategoryAttribute ("Behavior")]
665 [DefaultValueAttribute (false)]
666 public virtual bool EnableSortingAndPagingCallbacks {
668 object ob = ViewState ["EnableSortingAndPagingCallbacks"];
669 if (ob != null) return (bool) ob;
673 if (value == EnableSortingAndPagingCallbacks)
675 ViewState ["EnableSortingAndPagingCallbacks"] = value;
680 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
681 [BrowsableAttribute (false)]
682 public virtual GridViewRow FooterRow {
685 for (int index = table.Rows.Count - 1; index >= 0; index--) {
686 GridViewRow row = (GridViewRow) table.Rows [index];
687 switch (row.RowType) {
688 case DataControlRowType.Separator:
689 case DataControlRowType.Pager:
691 case DataControlRowType.Footer:
702 [WebCategoryAttribute ("Styles")]
703 [PersistenceMode (PersistenceMode.InnerProperty)]
704 [NotifyParentProperty (true)]
705 [DefaultValue (null)]
706 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
707 public TableItemStyle FooterStyle {
709 if (footerStyle == null) {
710 footerStyle = new TableItemStyle ();
711 if (IsTrackingViewState)
712 footerStyle.TrackViewState();
718 [WebCategoryAttribute ("Appearance")]
719 [DefaultValueAttribute (GridLines.Both)]
720 public virtual GridLines GridLines {
722 if (ControlStyleCreated)
723 return ((TableStyle) ControlStyle).GridLines;
724 return GridLines.Both;
727 ((TableStyle) ControlStyle).GridLines = value;
731 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
732 [BrowsableAttribute (false)]
733 public virtual GridViewRow HeaderRow {
736 for (int index = 0, total = table.Rows.Count; index < total; index++) {
737 GridViewRow row = (GridViewRow) table.Rows [index];
738 switch (row.RowType) {
739 case DataControlRowType.Separator:
740 case DataControlRowType.Pager:
742 case DataControlRowType.Header:
753 [WebCategoryAttribute ("Styles")]
754 [PersistenceMode (PersistenceMode.InnerProperty)]
755 [NotifyParentProperty (true)]
756 [DefaultValue (null)]
757 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
758 public TableItemStyle HeaderStyle {
760 if (headerStyle == null) {
761 headerStyle = new TableItemStyle ();
762 if (IsTrackingViewState)
763 headerStyle.TrackViewState();
769 [Category ("Layout")]
770 [DefaultValueAttribute (HorizontalAlign.NotSet)]
771 public virtual HorizontalAlign HorizontalAlign {
773 if (ControlStyleCreated)
774 return ((TableStyle) ControlStyle).HorizontalAlign;
775 return HorizontalAlign.NotSet;
778 ((TableStyle) ControlStyle).HorizontalAlign = value;
782 [BrowsableAttribute (false)]
783 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
784 public virtual int PageCount {
786 return ViewState.GetInt ("PageCount", 0);
789 ViewState ["PageCount"] = value;
793 [WebCategoryAttribute ("Paging")]
794 [BrowsableAttribute (true)]
795 [DefaultValueAttribute (0)]
796 public virtual int PageIndex {
801 if (value == pageIndex)
808 [DefaultValueAttribute (10)]
809 [WebCategoryAttribute ("Paging")]
810 public virtual int PageSize {
812 object ob = ViewState ["PageSize"];
813 if (ob != null) return (int) ob;
817 if (value == PageSize)
819 ViewState ["PageSize"] = value;
824 [WebCategoryAttribute ("Paging")]
825 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
826 [NotifyParentPropertyAttribute (true)]
827 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
828 public virtual PagerSettings PagerSettings {
830 if (pagerSettings == null) {
831 pagerSettings = new PagerSettings (this);
832 if (IsTrackingViewState)
833 ((IStateManager)pagerSettings).TrackViewState ();
835 return pagerSettings;
839 [WebCategoryAttribute ("Styles")]
840 [PersistenceMode (PersistenceMode.InnerProperty)]
841 [NotifyParentProperty (true)]
842 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
843 public TableItemStyle PagerStyle {
845 if (pagerStyle == null) {
846 pagerStyle = new TableItemStyle ();
847 if (IsTrackingViewState)
848 pagerStyle.TrackViewState();
855 [DefaultValue (null)]
856 /* DataControlPagerCell isnt specified in the docs */
857 //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
858 [PersistenceMode (PersistenceMode.InnerProperty)]
860 public virtual ITemplate PagerTemplate {
861 get { return pagerTemplate; }
862 set { pagerTemplate = value; }
865 [DefaultValueAttribute ("")]
866 [WebCategoryAttribute ("Accessibility")]
867 // [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
868 public virtual string RowHeaderColumn {
870 object ob = ViewState ["RowHeaderColumn"];
871 if (ob != null) return (string) ob;
875 if (value == RowHeaderColumn)
877 ViewState ["RowHeaderColumn"] = value;
882 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
883 [BrowsableAttribute (false)]
884 public virtual GridViewRowCollection Rows {
886 EnsureChildControls ();
888 rows = new GridViewRowCollection (new ArrayList ());
893 [WebCategoryAttribute ("Styles")]
894 [PersistenceMode (PersistenceMode.InnerProperty)]
895 [NotifyParentProperty (true)]
896 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
897 public TableItemStyle RowStyle {
899 if (rowStyle == null) {
900 rowStyle = new TableItemStyle ();
901 if (IsTrackingViewState)
902 rowStyle.TrackViewState();
908 [BrowsableAttribute (false)]
909 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
910 public virtual DataKey SelectedDataKey {
912 if (DataKeyNames.Length == 0)
913 throw new InvalidOperationException (String.Format ("Data keys must be specified on GridView '{0}' before the selected data keys can be retrieved. Use the DataKeyNames property to specify data keys.", ID));
915 if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
916 return DataKeys [selectedIndex];
922 [BindableAttribute (true)]
923 [DefaultValueAttribute (-1)]
924 public virtual int SelectedIndex {
926 return selectedIndex;
929 if (rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
930 int oldIndex = selectedIndex;
932 Rows [oldIndex].RowState = GetRowState (oldIndex);
934 selectedIndex = value;
935 if (rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
936 Rows [selectedIndex].RowState = GetRowState (selectedIndex);
941 [BrowsableAttribute (false)]
942 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
943 public virtual GridViewRow SelectedRow {
945 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
946 return Rows [selectedIndex];
952 [WebCategoryAttribute ("Styles")]
953 [PersistenceMode (PersistenceMode.InnerProperty)]
954 [NotifyParentProperty (true)]
955 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
956 public TableItemStyle SelectedRowStyle {
958 if (selectedRowStyle == null) {
959 selectedRowStyle = new TableItemStyle ();
960 if (IsTrackingViewState)
961 selectedRowStyle.TrackViewState();
963 return selectedRowStyle;
967 [BrowsableAttribute (false)]
968 public object SelectedValue {
970 if (SelectedDataKey != null)
971 return SelectedDataKey.Value;
977 [WebCategoryAttribute ("Appearance")]
978 [DefaultValueAttribute (false)]
979 public virtual bool ShowFooter {
981 object ob = ViewState ["ShowFooter"];
982 if (ob != null) return (bool) ob;
986 if (value == ShowFooter)
988 ViewState ["ShowFooter"] = value;
993 [WebCategoryAttribute ("Appearance")]
994 [DefaultValueAttribute (true)]
995 public virtual bool ShowHeader {
997 object ob = ViewState ["ShowHeader"];
998 if (ob != null) return (bool) ob;
1002 if (value == ShowHeader)
1004 ViewState ["ShowHeader"] = value;
1009 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
1010 [BrowsableAttribute (false)]
1011 [DefaultValueAttribute (SortDirection.Ascending)]
1012 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1013 public virtual SortDirection SortDirection {
1014 get { return sortDirection; }
1016 if (sortDirection == value)
1018 sortDirection = value;
1023 [BrowsableAttribute (false)]
1024 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1025 public virtual string SortExpression {
1027 if (sortExpression == null)
1028 return String.Empty;
1029 return sortExpression;
1032 if (sortExpression == value)
1034 sortExpression = value;
1039 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1040 [BrowsableAttribute (false)]
1041 public virtual GridViewRow TopPagerRow {
1048 [WebCategoryAttribute ("Accessibility")]
1049 [DefaultValueAttribute (true)]
1050 public virtual bool UseAccessibleHeader {
1052 object ob = ViewState ["UseAccessibleHeader"];
1053 if (ob != null) return (bool) ob;
1057 if (value == UseAccessibleHeader)
1059 ViewState ["UseAccessibleHeader"] = value;
1064 public virtual bool IsBindableType (Type type)
1066 return type.IsPrimitive || type == typeof (string) || type == typeof (decimal) || type == typeof (DateTime) || type == typeof (Guid);
1069 // MSDN: The CreateDataSourceSelectArguments method is a helper method called by
1070 // the GridView control to create the DataSourceSelectArguments object that
1071 // contains the arguments passed to the data source. In this implementation,
1072 // the DataSourceSelectArguments object contains the arguments for paging operations.
1073 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
1075 DataSourceSelectArguments arg = DataSourceSelectArguments.Empty;
1076 DataSourceView view= GetData();
1077 if (AllowPaging && view.CanPage) {
1078 arg.StartRowIndex = PageIndex * PageSize;
1079 if (view.CanRetrieveTotalRowCount) {
1080 arg.RetrieveTotalRowCount = true;
1081 arg.MaximumRows = PageSize;
1084 arg.MaximumRows = -1;
1088 if (IsBoundUsingDataSourceID && !String.IsNullOrEmpty (sortExpression)) {
1089 if (sortDirection == SortDirection.Ascending)
1090 arg.SortExpression = sortExpression;
1092 arg.SortExpression = sortExpression + " DESC";
1098 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
1100 ArrayList fields = new ArrayList ();
1102 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
1103 CommandField field = new CommandField ();
1104 field.ShowEditButton = AutoGenerateEditButton;
1105 field.ShowDeleteButton = AutoGenerateDeleteButton;
1106 field.ShowSelectButton = AutoGenerateSelectButton;
1110 fields.AddRange (Columns);
1112 if (AutoGenerateColumns) {
1114 autoFieldProperties = CreateAutoFieldProperties (dataSource);
1116 if (autoFieldProperties != null) {
1117 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
1118 fields.Add (CreateAutoGeneratedColumn (props));
1125 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
1127 return new AutoGeneratedField (fieldProperties);
1130 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
1132 if(source == null) return null;
1134 PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
1137 ArrayList retVal = new ArrayList();
1141 object fitem = null;
1143 PropertyInfo prop_item = source.DataSource.GetType().GetProperty("Item",
1144 BindingFlags.Instance | BindingFlags.Static |
1145 BindingFlags.Public, null, null,
1146 new Type[] { typeof(int) }, null);
1148 if (prop_item != null) {
1149 prop_type = prop_item.PropertyType;
1152 if (prop_type == null || prop_type == typeof(object)) {
1153 IEnumerator en = source.GetEnumerator();
1154 if (en != null && en.MoveNext ()) {
1156 _dataEnumerator = en;
1159 prop_type = fitem.GetType();
1162 if (fitem != null && fitem is ICustomTypeDescriptor) {
1163 props = TypeDescriptor.GetProperties(fitem);
1164 } else if (prop_type != null) {
1165 if (IsBindableType (prop_type)) {
1166 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1167 ((IStateManager)field).TrackViewState();
1168 field.Name = "Item";
1169 field.DataField = BoundField.ThisExpression;
1170 field.Type = prop_type;
1173 props = TypeDescriptor.GetProperties (prop_type);
1178 if (props != null && props.Count > 0)
1180 foreach (PropertyDescriptor current in props) {
1181 if (IsBindableType (current.PropertyType)) {
1182 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1183 ((IStateManager)field).TrackViewState();
1184 field.Name = current.Name;
1185 field.DataField = current.Name;
1186 for (int i = 0; i < DataKeyNames.Length; i++) {
1187 if (string.Compare (DataKeyNames [i], current.Name, StringComparison.InvariantCultureIgnoreCase) == 0) {
1188 field.IsReadOnly = true;
1192 field.Type = current.PropertyType;
1198 if (retVal.Count > 0)
1199 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1201 return new AutoGeneratedFieldProperties [0];
1204 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1206 GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1210 void RequireBinding ()
1213 RequiresDataBinding = true;
1217 protected virtual Table CreateChildTable ()
1219 return new ContainedTable (this);
1222 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1233 PagedDataSource dataSource;
1236 DataSourceView view = GetData ();
1237 dataSource = new PagedDataSource ();
1238 dataSource.DataSource = data;
1241 dataSource.AllowPaging = true;
1242 dataSource.PageSize = PageSize;
1244 dataSource.AllowServerPaging = true;
1245 if (SelectArguments.RetrieveTotalRowCount)
1246 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1248 if (PageIndex >= dataSource.PageCount)
1249 pageIndex = dataSource.PageCount - 1;
1250 dataSource.CurrentPageIndex = PageIndex;
1253 PageCount = dataSource.PageCount;
1257 dataSource = new PagedDataSource ();
1258 dataSource.DataSource = data;
1260 dataSource.AllowPaging = true;
1261 dataSource.PageSize = PageSize;
1262 dataSource.CurrentPageIndex = PageIndex;
1266 bool createPager = AllowPaging && (PageCount >= 1) && PagerSettings.Visible;
1268 ArrayList list = new ArrayList ();
1270 // Creates the set of fields to show
1272 _dataEnumerator = null;
1273 ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1274 DataControlField[] fields = new DataControlField [fieldCollection.Count];
1275 fieldCollection.CopyTo (fields, 0);
1277 foreach (DataControlField field in fields) {
1278 field.Initialize (AllowSorting, this);
1279 if (EnableSortingAndPagingCallbacks)
1280 field.ValidateSupportsCallback ();
1283 bool skip_first = false;
1284 IEnumerator enumerator;
1285 if (_dataEnumerator != null) {
1286 // replaced when creating bound columns
1287 enumerator = _dataEnumerator;
1291 enumerator = dataSource.GetEnumerator ();
1294 // Main table creation
1295 while (skip_first || enumerator.MoveNext ()) {
1297 object obj = enumerator.Current;
1299 if (list.Count == 0) {
1300 if (createPager && (PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom)) {
1301 topPagerRow = CreatePagerRow (fields.Length, dataSource);
1302 OnRowCreated (new GridViewRowEventArgs (topPagerRow));
1303 ContainedTable.Rows.Add (topPagerRow);
1305 topPagerRow.DataBind ();
1306 OnRowDataBound (new GridViewRowEventArgs (topPagerRow));
1309 topPagerRow.Visible = false;
1312 GridViewRow headerRow = CreateRow (-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
1313 InitializeRow (headerRow, fields);
1314 OnRowCreated (new GridViewRowEventArgs (headerRow));
1315 ContainedTable.Rows.Add (headerRow);
1317 headerRow.DataBind ();
1318 OnRowDataBound (new GridViewRowEventArgs (headerRow));
1322 DataControlRowState rstate = GetRowState (list.Count);
1323 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1326 InitializeRow (row, fields);
1327 OnRowCreated (new GridViewRowEventArgs (row));
1328 ContainedTable.Rows.Add (row);
1331 OnRowDataBound (new GridViewRowEventArgs (row));
1332 if (EditIndex == row.RowIndex)
1333 oldEditValues = new DataKey (GetRowValues (row, true, true));
1334 DataKeyArrayList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1338 if (list.Count == 0) {
1339 GridViewRow emptyRow = CreateEmptyrRow (fields.Length);
1340 if (emptyRow != null) {
1341 OnRowCreated (new GridViewRowEventArgs (emptyRow));
1342 ContainedTable.Rows.Add (emptyRow);
1344 emptyRow.DataBind ();
1345 OnRowDataBound (new GridViewRowEventArgs (emptyRow));
1351 GridViewRow footerRow = CreateRow (-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
1352 InitializeRow (footerRow, fields);
1353 OnRowCreated (new GridViewRowEventArgs (footerRow));
1354 ContainedTable.Rows.Add (footerRow);
1356 footerRow.DataBind ();
1357 OnRowDataBound (new GridViewRowEventArgs (footerRow));
1360 if (createPager && (PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom)) {
1361 bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
1362 OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
1363 ContainedTable.Rows.Add (bottomPagerRow);
1365 bottomPagerRow.DataBind ();
1366 OnRowDataBound (new GridViewRowEventArgs (bottomPagerRow));
1369 bottomPagerRow.Visible = false;
1373 rows = new GridViewRowCollection (list);
1379 return dataSource.DataSourceCount;
1384 Table ContainedTable {
1386 if (table == null) {
1387 table = CreateChildTable ();
1388 Controls.Add (table);
1394 protected override Style CreateControlStyle ()
1396 TableStyle style = new TableStyle (ViewState);
1397 style.GridLines = GridLines.Both;
1398 style.CellSpacing = 0;
1402 DataControlRowState GetRowState (int index)
1404 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1405 if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1406 if (index == EditIndex) rstate |= DataControlRowState.Edit;
1410 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1412 GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1413 InitializePager (row, fieldCount, dataSource);
1417 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1419 TableCell cell = new TableCell ();
1421 cell.ColumnSpan = columnSpan;
1423 if (pagerTemplate != null)
1424 pagerTemplate.InstantiateIn (cell);
1426 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1428 row.Cells.Add (cell);
1431 GridViewRow CreateEmptyrRow (int fieldCount)
1433 if (emptyDataTemplate == null && String.IsNullOrEmpty (EmptyDataText))
1436 GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1437 TableCell cell = new TableCell ();
1438 cell.ColumnSpan = fieldCount;
1440 if (emptyDataTemplate != null)
1441 emptyDataTemplate.InstantiateIn (cell);
1443 cell.Text = EmptyDataText;
1445 row.Cells.Add (cell);
1449 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1451 DataControlCellType ctype;
1452 bool accessibleHeader = false;
1454 switch (row.RowType) {
1455 case DataControlRowType.Header:
1456 ctype = DataControlCellType.Header;
1457 accessibleHeader = UseAccessibleHeader;
1459 case DataControlRowType.Footer:
1460 ctype = DataControlCellType.Footer;
1463 ctype = DataControlCellType.DataCell;
1467 for (int n=0; n<fields.Length; n++) {
1468 DataControlField field = fields [n];
1470 DataControlFieldCell cell;
1471 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1472 cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1474 cell = new DataControlFieldCell (field);
1475 row.Cells.Add (cell);
1476 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1480 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1482 if (cachedKeyProperties == null) {
1483 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1484 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1485 for (int n=0; n<DataKeyNames.Length; n++) {
1486 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1488 throw new InvalidOperationException ("Property '" + DataKeyNames [n] + "' not found in object of type " + row.DataItem.GetType ());
1489 cachedKeyProperties [n] = p;
1493 OrderedDictionary dic = new OrderedDictionary ();
1494 foreach (PropertyDescriptor p in cachedKeyProperties)
1495 dic [p.Name] = p.GetValue (row.DataItem);
1499 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1501 OrderedDictionary dic = new OrderedDictionary ();
1502 ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1506 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1508 DataControlField field;
1509 foreach (TableCell cell in row.Cells) {
1510 DataControlFieldCell c = cell as DataControlFieldCell;
1514 field = c.ContainingField;
1515 if (field != null && !field.Visible)
1518 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1520 if (!includePrimaryKey && DataKeyNames != null)
1521 foreach (string key in DataKeyNames)
1522 fieldValues.Remove (key);
1525 protected override HtmlTextWriterTag TagKey {
1527 if (EnableSortingAndPagingCallbacks)
1528 return HtmlTextWriterTag.Div;
1530 return HtmlTextWriterTag.Table;
1534 public sealed override void DataBind ()
1536 DataKeyArrayList.Clear ();
1537 cachedKeyProperties = null;
1540 keys = new DataKeyArray (DataKeyArrayList);
1543 protected internal override void PerformDataBinding (IEnumerable data)
1545 base.PerformDataBinding (data);
1548 protected internal virtual void PrepareControlHierarchy ()
1553 table.Caption = Caption;
1554 table.CaptionAlign = CaptionAlign;
1555 table.CopyBaseAttributes (this);
1557 foreach (GridViewRow row in table.Rows) {
1558 switch (row.RowType) {
1559 case DataControlRowType.Header:
1560 if (headerStyle != null && !headerStyle.IsEmpty)
1561 row.ControlStyle.MergeWith(headerStyle);
1562 row.Visible = ShowHeader;
1564 case DataControlRowType.Footer:
1565 if (footerStyle != null && !footerStyle.IsEmpty)
1566 row.ControlStyle.MergeWith (footerStyle);
1567 row.Visible = ShowFooter;
1569 case DataControlRowType.Pager:
1570 if (pagerStyle != null && !pagerStyle.IsEmpty)
1571 row.ControlStyle.MergeWith (pagerStyle);
1573 case DataControlRowType.EmptyDataRow:
1574 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1575 row.ControlStyle.MergeWith (emptyDataRowStyle);
1577 case DataControlRowType.DataRow:
1578 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1579 row.ControlStyle.MergeWith (editRowStyle);
1580 if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null && !selectedRowStyle.IsEmpty)
1581 row.ControlStyle.MergeWith (selectedRowStyle);
1582 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1583 row.ControlStyle.MergeWith (alternatingRowStyle);
1584 if (rowStyle != null && !rowStyle.IsEmpty)
1585 row.ControlStyle.MergeWith (rowStyle);
1591 foreach (TableCell cell in row.Cells) {
1592 DataControlFieldCell fcell = cell as DataControlFieldCell;
1593 if (fcell != null) {
1594 DataControlField field = fcell.ContainingField;
1597 if (!field.Visible) {
1598 cell.Visible = false;
1602 switch (row.RowType) {
1603 case DataControlRowType.Header:
1604 if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1605 cell.ControlStyle.MergeWith (field.HeaderStyle);
1607 case DataControlRowType.Footer:
1608 if (field.FooterStyleCreated && !field.FooterStyle.IsEmpty)
1609 cell.ControlStyle.MergeWith (field.FooterStyle);
1612 if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1613 foreach (Control c in cell.Controls) {
1614 WebControl wc = c as WebControl;
1616 wc.ControlStyle.MergeWith (field.ControlStyle);
1618 if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1619 cell.ControlStyle.MergeWith (field.ItemStyle);
1627 protected internal override void OnInit (EventArgs e)
1629 Page.RegisterRequiresControlState (this);
1633 void OnFieldsChanged (object sender, EventArgs args)
1638 protected override void OnDataPropertyChanged ()
1640 base.OnDataPropertyChanged ();
1644 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1646 base.OnDataSourceViewChanged (sender, e);
1650 protected override bool OnBubbleEvent (object source, EventArgs e)
1652 GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1654 bool causesValidation = false;
1655 IButtonControl button = args.CommandSource as IButtonControl;
1656 if (button != null && button.CausesValidation) {
1657 Page.Validate (button.ValidationGroup);
1658 causesValidation = true;
1660 OnRowCommand (args);
1661 string param = args.CommandArgument as string;
1662 if (param == null || param.Length == 0) {
1663 GridViewRow row = args.Row;
1665 param = row.RowIndex.ToString();
1667 ProcessEvent (args.CommandName, param, causesValidation);
1670 return base.OnBubbleEvent (source, e);
1673 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1675 RaisePostBackEvent (eventArgument);
1678 // This is prolly obsolete
1679 protected virtual void RaisePostBackEvent (string eventArgument)
1681 GridViewCommandEventArgs args;
1682 int i = eventArgument.IndexOf ('$');
1684 args = new GridViewCommandEventArgs (this, new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1)));
1686 args = new GridViewCommandEventArgs (this, new CommandEventArgs (eventArgument, null));
1688 OnRowCommand (args);
1689 ProcessEvent (args.CommandName, (string) args.CommandArgument, false);
1692 void ProcessEvent (string eventName, string param, bool causesValidation)
1696 case DataControlCommands.PageCommandName:
1699 case DataControlCommands.FirstPageCommandArgument:
1702 case DataControlCommands.LastPageCommandArgument:
1703 newIndex = PageCount - 1;
1705 case DataControlCommands.NextPageCommandArgument:
1706 newIndex = PageIndex + 1;
1708 case DataControlCommands.PreviousPageCommandArgument:
1709 newIndex = PageIndex - 1;
1713 int.TryParse (param, out paramIndex);
1714 newIndex = paramIndex - 1;
1717 ShowPage (newIndex);
1720 case DataControlCommands.FirstPageCommandArgument:
1724 case DataControlCommands.LastPageCommandArgument:
1725 ShowPage (PageCount - 1);
1728 case DataControlCommands.NextPageCommandArgument:
1729 if (PageIndex < PageCount - 1)
1730 ShowPage (PageIndex + 1);
1733 case DataControlCommands.PreviousPageCommandArgument:
1735 ShowPage (PageIndex - 1);
1738 case DataControlCommands.SelectCommandName:
1739 SelectRow (int.Parse (param));
1742 case DataControlCommands.EditCommandName:
1743 EditRow (int.Parse (param));
1746 case DataControlCommands.UpdateCommandName:
1747 int editIndex = int.Parse (param);
1748 UpdateRow (Rows [editIndex], editIndex, causesValidation);
1751 case DataControlCommands.CancelCommandName:
1755 case DataControlCommands.DeleteCommandName:
1756 DeleteRow (int.Parse (param));
1759 case DataControlCommands.SortCommandName:
1765 void Sort (string newSortExpression)
1767 SortDirection newDirection = SortDirection.Ascending;
1768 if (sortExpression == newSortExpression && sortDirection == SortDirection.Ascending)
1769 newDirection = SortDirection.Descending;
1771 Sort (newSortExpression, newDirection);
1774 public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
1776 GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1778 if (args.Cancel) return;
1780 if (IsBoundUsingDataSourceID) {
1783 SortExpression = args.SortExpression;
1784 SortDirection = args.SortDirection;
1787 OnSorted (EventArgs.Empty);
1790 void SelectRow (int index)
1792 GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1793 OnSelectedIndexChanging (args);
1796 SelectedIndex = args.NewSelectedIndex;
1797 OnSelectedIndexChanged (EventArgs.Empty);
1801 void ShowPage (int newIndex)
1803 GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1804 OnPageIndexChanging (args);
1806 if (args.Cancel || !IsBoundUsingDataSourceID)
1810 PageIndex = args.NewPageIndex;
1811 OnPageIndexChanged (EventArgs.Empty);
1814 void EditRow (int index)
1816 GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1817 OnRowEditing (args);
1819 if (args.Cancel || !IsBoundUsingDataSourceID)
1822 EditIndex = args.NewEditIndex;
1827 GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1828 OnRowCancelingEdit (args);
1830 if (args.Cancel || !IsBoundUsingDataSourceID)
1836 [MonoTODO ("Support two-way binding expressions")]
1837 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1839 if (rowIndex != EditIndex) throw new NotSupportedException ();
1841 GridViewRow row = Rows [rowIndex];
1842 UpdateRow (row, rowIndex, causesValidation);
1845 void UpdateRow (GridViewRow row, int rowIndex, bool causesValidation)
1847 if (causesValidation && Page != null && !Page.IsValid)
1850 currentEditOldValues = CopyOrderedDictionary (OldEditValues.Values);
1851 currentEditRowKeys = CopyOrderedDictionary (DataKeys [rowIndex].Values);
1852 currentEditNewValues = GetRowValues (row, false, false);
1854 GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (rowIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1855 OnRowUpdating (args);
1857 if (args.Cancel || !IsBoundUsingDataSourceID)
1860 DataSourceView view = GetData ();
1862 throw new HttpException ("The DataSourceView associated to data bound control was null");
1863 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1866 static IOrderedDictionary CopyOrderedDictionary (IOrderedDictionary sourceDic) {
1867 OrderedDictionary copyDic = new OrderedDictionary ();
1868 foreach (object key in sourceDic.Keys) {
1869 copyDic.Add (key, sourceDic [key]);
1874 bool UpdateCallback (int recordsAffected, Exception exception)
1876 GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1877 OnRowUpdated (dargs);
1879 if (!dargs.KeepInEditMode)
1882 return dargs.ExceptionHandled;
1885 public virtual void DeleteRow (int rowIndex)
1887 GridViewRow row = Rows [rowIndex];
1888 currentEditRowKeys = CopyOrderedDictionary (DataKeys [rowIndex].Values);
1889 currentEditNewValues = GetRowValues (row, true, true);
1891 GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1892 OnRowDeleting (args);
1894 if (args.Cancel || !IsBoundUsingDataSourceID)
1898 DataSourceView view = GetData ();
1900 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1902 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1903 OnRowDeleted (dargs);
1907 bool DeleteCallback (int recordsAffected, Exception exception)
1909 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1910 OnRowDeleted (dargs);
1911 return dargs.ExceptionHandled;
1917 oldEditValues = new DataKey (new OrderedDictionary ());
1918 currentEditRowKeys = null;
1919 currentEditOldValues = null;
1920 currentEditNewValues = null;
1923 protected internal override void LoadControlState (object ob)
1925 if (ob == null) return;
1926 object[] state = (object[]) ob;
1927 base.LoadControlState (state[0]);
1928 pageIndex = (int) state[1];
1929 selectedIndex = (int) state[2];
1930 editIndex = (int) state[3];
1931 sortExpression = (string) state[4];
1932 sortDirection = (SortDirection) state[5];
1933 DataKeyNames = (string []) state [6];
1934 if (state [7] != null)
1935 LoadDataKeyArrayState ((object []) state [7]);
1936 if (state [8] != null)
1937 ((IStateManager) OldEditValues).LoadViewState (state [8]);
1940 protected internal override object SaveControlState ()
1942 if (EnableSortingAndPagingCallbacks) {
1943 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1944 Page.ClientScript.RegisterHiddenField (ClientID + "_SortExpression", SortExpression);
1945 Page.ClientScript.RegisterHiddenField (ClientID + "_SortDirection", ((int)SortDirection).ToString());
1948 object bstate = base.SaveControlState ();
1949 return new object [] {
1957 SaveDataKeyArrayState (),
1958 (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState ())
1962 object [] SaveDataKeyArrayState ()
1967 object [] state = new object [keys.Count];
1968 for (int i = 0; i < keys.Count; i++) {
1969 state [i] = ((IStateManager) keys [i]).SaveViewState ();
1974 void LoadDataKeyArrayState (object [] state)
1976 for (int i = 0; i < state.Length; i++) {
1977 DataKey dataKey = new DataKey (new OrderedDictionary (DataKeyNames.Length), DataKeyNames);
1978 ((IStateManager) dataKey).LoadViewState (state [i]);
1979 DataKeyArrayList.Add (dataKey);
1981 keys = new DataKeyArray (DataKeyArrayList);
1984 protected override void TrackViewState()
1986 base.TrackViewState();
1987 if (columns != null) ((IStateManager)columns).TrackViewState();
1988 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1989 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1990 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1991 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1992 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1993 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1994 if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
1995 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1996 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1997 if (keys != null) ((IStateManager)keys).TrackViewState();
1998 if (autoFieldProperties != null) {
1999 foreach (IStateManager sm in autoFieldProperties)
2000 sm.TrackViewState ();
2004 protected override object SaveViewState()
2006 object[] states = new object [12];
2007 states[0] = base.SaveViewState();
2008 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
2009 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
2010 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
2011 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
2012 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
2013 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
2014 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
2015 states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
2016 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
2017 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
2019 if (autoFieldProperties != null) {
2020 object[] data = new object [autoFieldProperties.Length];
2021 bool allNull = true;
2022 for (int n=0; n<data.Length; n++) {
2023 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
2024 if (data [n] != null) allNull = false;
2026 if (!allNull) states [11] = data;
2029 for (int i = states.Length - 1; i >= 0; i--) {
2030 if (states [i] != null)
2037 protected override void LoadViewState (object savedState)
2039 if (savedState == null) {
2040 base.LoadViewState (null);
2044 object [] states = (object []) savedState;
2046 if (states[11] != null) {
2047 object[] data = (object[]) states [11];
2048 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
2049 for (int n=0; n<data.Length; n++) {
2050 IStateManager p = new AutoGeneratedFieldProperties ();
2051 p.TrackViewState ();
2052 p.LoadViewState (data [n]);
2053 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
2057 base.LoadViewState (states[0]);
2059 if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
2060 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
2061 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
2062 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
2063 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
2064 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
2065 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
2066 if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
2067 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
2068 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
2071 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
2073 RaiseCallbackEvent (eventArgs);
2076 protected virtual void RaiseCallbackEvent (string eventArgs)
2078 string[] clientData = eventArgs.Split ('|');
2079 PageIndex = int.Parse (clientData[0]);
2080 SortExpression = HttpUtility.UrlDecode (clientData [1]);
2081 SortDirection = (SortDirection) int.Parse (clientData [2]);
2083 RaisePostBackEvent (clientData[3]);
2087 string ICallbackEventHandler.GetCallbackResult ()
2089 return GetCallbackResult ();
2092 protected virtual string GetCallbackResult ()
2094 PrepareControlHierarchy ();
2096 StringWriter sw = new StringWriter ();
2097 sw.Write (PageIndex.ToString () + '|' + SortExpression + '|' + (int) SortDirection + '|');
2099 HtmlTextWriter writer = new HtmlTextWriter (sw);
2100 RenderGrid (writer);
2101 return sw.ToString ();
2104 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
2106 return GetCallbackScript (control, argument);
2109 protected virtual string GetCallbackScript (IButtonControl control, string argument)
2111 if (EnableSortingAndPagingCallbacks)
2112 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
2117 protected override void OnPagePreLoad (object sender, EventArgs e)
2119 base.OnPagePreLoad (sender, e);
2121 if (Page.IsPostBack && EnableSortingAndPagingCallbacks) {
2123 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
2126 if (int.TryParse (Page.Request.Form [ClientID + "_SortDirection"], out dir))
2127 SortDirection = (SortDirection) dir;
2128 SortExpression = Page.Request.Form [ClientID + "_SortExpression"];
2133 const string onPreRenderScript = @"var {0} = new Object ();
2134 {0}.pageIndex = {1};
2140 protected internal override void OnPreRender (EventArgs e)
2142 base.OnPreRender (e);
2144 if (EnableSortingAndPagingCallbacks) {
2145 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
2146 string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
2147 Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
2150 string cgrid = ClientID + "_data";
2151 string script = String.Format (onPreRenderScript,
2153 ClientScriptManager.GetScriptLiteral (PageIndex),
2154 ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression),
2155 ClientScriptManager.GetScriptLiteral ((int) SortDirection),
2156 ClientScriptManager.GetScriptLiteral (UniqueID),
2159 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
2161 // Make sure the basic script infrastructure is rendered
2162 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
2163 Page.ClientScript.GetPostBackClientHyperlink (this, "");
2167 protected internal override void Render (HtmlTextWriter writer)
2169 PrepareControlHierarchy ();
2171 if (EnableSortingAndPagingCallbacks)
2172 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_div");
2173 writer.RenderBeginTag (HtmlTextWriterTag.Div);
2175 RenderGrid (writer);
2177 writer.RenderEndTag ();
2180 void RenderGrid (HtmlTextWriter writer)
2185 table.Render (writer);
2188 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
2190 if (control == null)
2191 throw new ArgumentNullException ("control");
2193 if (control.CausesValidation)
2194 throw new InvalidOperationException ("A button that causes validation in GridView '" + ID + "' is attempting to use the container GridView as the post back target. The button should either turn off validation or use itself as the post back container.");
2196 PostBackOptions options = new PostBackOptions (this);
2197 options.Argument = control.CommandName + "$" + control.CommandArgument;
2198 options.RequiresJavaScriptProtocol = true;