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, IPersistedSelector
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 static readonly object PageIndexChangedEvent = new object();
86 static readonly object PageIndexChangingEvent = new object();
87 static readonly object RowCancelingEditEvent = new object();
88 static readonly object RowCommandEvent = new object();
89 static readonly object RowCreatedEvent = new object();
90 static readonly object RowDataBoundEvent = new object();
91 static readonly object RowDeletedEvent = new object();
92 static readonly object RowDeletingEvent = new object();
93 static readonly object RowEditingEvent = new object();
94 static readonly object RowUpdatedEvent = new object();
95 static readonly object RowUpdatingEvent = new object();
96 static readonly object SelectedIndexChangedEvent = new object();
97 static readonly object SelectedIndexChangingEvent = new object();
98 static readonly object SortedEvent = new object();
99 static readonly object SortingEvent = new object();
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 [BrowsableAttribute(false)]
547 public IAutoFieldGenerator ColumnsGenerator {
552 [DefaultValueAttribute (null)]
553 [WebCategoryAttribute ("Data")]
554 [TypeConverter (typeof(StringArrayConverter))]
555 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
556 public virtual string[] DataKeyNames
559 if (dataKeyNames != null)
564 dataKeyNames = value;
569 ArrayList DataKeyArrayList {
571 if (_dataKeyArrayList == null) {
572 _dataKeyArrayList = new ArrayList ();
574 return _dataKeyArrayList;
578 [BrowsableAttribute (false)]
579 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
580 public virtual DataKeyArray DataKeys {
583 keys = new DataKeyArray (DataKeyArrayList);
584 if (IsTrackingViewState)
585 ((IStateManager) keys).TrackViewState ();
591 DataKey OldEditValues {
593 if (oldEditValues == null) {
594 oldEditValues = new DataKey (new OrderedDictionary ());
596 return oldEditValues;
600 [WebCategoryAttribute ("Misc")]
601 [DefaultValueAttribute (-1)]
602 public virtual int EditIndex {
607 if (value == editIndex)
614 [WebCategoryAttribute ("Styles")]
615 [PersistenceMode (PersistenceMode.InnerProperty)]
616 [NotifyParentProperty (true)]
617 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
618 public TableItemStyle EditRowStyle {
620 if (editRowStyle == null) {
621 editRowStyle = new TableItemStyle ();
622 if (IsTrackingViewState)
623 editRowStyle.TrackViewState();
629 [WebCategoryAttribute ("Styles")]
630 [PersistenceMode (PersistenceMode.InnerProperty)]
631 [NotifyParentProperty (true)]
632 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
633 public TableItemStyle EmptyDataRowStyle {
635 if (emptyDataRowStyle == null) {
636 emptyDataRowStyle = new TableItemStyle ();
637 if (IsTrackingViewState)
638 emptyDataRowStyle.TrackViewState();
640 return emptyDataRowStyle;
644 [DefaultValue (null)]
645 [TemplateContainer (typeof(GridViewRow), BindingDirection.OneWay)]
646 [PersistenceMode (PersistenceMode.InnerProperty)]
648 public virtual ITemplate EmptyDataTemplate {
649 get { return emptyDataTemplate; }
650 set { emptyDataTemplate = value; }
653 [LocalizableAttribute (true)]
654 [WebCategoryAttribute ("Appearance")]
655 [DefaultValueAttribute ("")]
656 public virtual string EmptyDataText {
658 object ob = ViewState ["EmptyDataText"];
659 if (ob != null) return (string) ob;
663 if (value == EmptyDataText)
665 ViewState ["EmptyDataText"] = value;
670 [WebCategoryAttribute ("Behavior")]
671 [DefaultValueAttribute (false)]
672 public virtual bool EnableSortingAndPagingCallbacks {
674 object ob = ViewState ["EnableSortingAndPagingCallbacks"];
675 if (ob != null) return (bool) ob;
679 if (value == EnableSortingAndPagingCallbacks)
681 ViewState ["EnableSortingAndPagingCallbacks"] = value;
686 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
687 [BrowsableAttribute (false)]
688 public virtual GridViewRow FooterRow {
691 for (int index = table.Rows.Count - 1; index >= 0; index--) {
692 GridViewRow row = (GridViewRow) table.Rows [index];
693 switch (row.RowType) {
694 case DataControlRowType.Separator:
695 case DataControlRowType.Pager:
697 case DataControlRowType.Footer:
708 [WebCategoryAttribute ("Styles")]
709 [PersistenceMode (PersistenceMode.InnerProperty)]
710 [NotifyParentProperty (true)]
711 [DefaultValue (null)]
712 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
713 public TableItemStyle FooterStyle {
715 if (footerStyle == null) {
716 footerStyle = new TableItemStyle ();
717 if (IsTrackingViewState)
718 footerStyle.TrackViewState();
724 [WebCategoryAttribute ("Appearance")]
725 [DefaultValueAttribute (GridLines.Both)]
726 public virtual GridLines GridLines {
728 if (ControlStyleCreated)
729 return ((TableStyle) ControlStyle).GridLines;
730 return GridLines.Both;
733 ((TableStyle) ControlStyle).GridLines = value;
737 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
738 [BrowsableAttribute (false)]
739 public virtual GridViewRow HeaderRow {
742 for (int index = 0, total = table.Rows.Count; index < total; index++) {
743 GridViewRow row = (GridViewRow) table.Rows [index];
744 switch (row.RowType) {
745 case DataControlRowType.Separator:
746 case DataControlRowType.Pager:
748 case DataControlRowType.Header:
759 [WebCategoryAttribute ("Styles")]
760 [PersistenceMode (PersistenceMode.InnerProperty)]
761 [NotifyParentProperty (true)]
762 [DefaultValue (null)]
763 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
764 public TableItemStyle HeaderStyle {
766 if (headerStyle == null) {
767 headerStyle = new TableItemStyle ();
768 if (IsTrackingViewState)
769 headerStyle.TrackViewState();
775 [Category ("Layout")]
776 [DefaultValueAttribute (HorizontalAlign.NotSet)]
777 public virtual HorizontalAlign HorizontalAlign {
779 if (ControlStyleCreated)
780 return ((TableStyle) ControlStyle).HorizontalAlign;
781 return HorizontalAlign.NotSet;
784 ((TableStyle) ControlStyle).HorizontalAlign = value;
788 [BrowsableAttribute (false)]
789 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
790 public virtual int PageCount {
792 return ViewState.GetInt ("PageCount", 0);
795 ViewState ["PageCount"] = value;
799 [WebCategoryAttribute ("Paging")]
800 [BrowsableAttribute (true)]
801 [DefaultValueAttribute (0)]
802 public virtual int PageIndex {
807 if (value == pageIndex)
814 [DefaultValueAttribute (10)]
815 [WebCategoryAttribute ("Paging")]
816 public virtual int PageSize {
818 object ob = ViewState ["PageSize"];
819 if (ob != null) return (int) ob;
823 if (value == PageSize)
825 ViewState ["PageSize"] = value;
830 [WebCategoryAttribute ("Paging")]
831 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
832 [NotifyParentPropertyAttribute (true)]
833 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
834 public virtual PagerSettings PagerSettings {
836 if (pagerSettings == null) {
837 pagerSettings = new PagerSettings (this);
838 if (IsTrackingViewState)
839 ((IStateManager)pagerSettings).TrackViewState ();
841 return pagerSettings;
845 [WebCategoryAttribute ("Styles")]
846 [PersistenceMode (PersistenceMode.InnerProperty)]
847 [NotifyParentProperty (true)]
848 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
849 public TableItemStyle PagerStyle {
851 if (pagerStyle == null) {
852 pagerStyle = new TableItemStyle ();
853 if (IsTrackingViewState)
854 pagerStyle.TrackViewState();
861 [DefaultValue (null)]
862 /* DataControlPagerCell isnt specified in the docs */
863 //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
864 [PersistenceMode (PersistenceMode.InnerProperty)]
866 public virtual ITemplate PagerTemplate {
867 get { return pagerTemplate; }
868 set { pagerTemplate = value; }
871 [DefaultValueAttribute ("")]
872 [WebCategoryAttribute ("Accessibility")]
873 // [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
874 public virtual string RowHeaderColumn {
876 object ob = ViewState ["RowHeaderColumn"];
877 if (ob != null) return (string) ob;
881 if (value == RowHeaderColumn)
883 ViewState ["RowHeaderColumn"] = value;
888 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
889 [BrowsableAttribute (false)]
890 public virtual GridViewRowCollection Rows {
892 EnsureChildControls ();
894 rows = new GridViewRowCollection (new ArrayList ());
899 [WebCategoryAttribute ("Styles")]
900 [PersistenceMode (PersistenceMode.InnerProperty)]
901 [NotifyParentProperty (true)]
902 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
903 public TableItemStyle RowStyle {
905 if (rowStyle == null) {
906 rowStyle = new TableItemStyle ();
907 if (IsTrackingViewState)
908 rowStyle.TrackViewState();
914 [BrowsableAttribute (false)]
915 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
916 public virtual DataKey SelectedDataKey {
918 if (DataKeyNames.Length == 0)
919 throw new InvalidOperationException (String.Format ("Data keys must be specified on GridView '{0}' before the selected data keys can be retrieved. Use the DataKeyNames property to specify data keys.", ID));
921 if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
922 return DataKeys [selectedIndex];
929 [BrowsableAttribute(false)]
930 public virtual DataKey SelectedPersistedDataKey {
935 DataKey IPersistedSelector.DataKey {
936 get { return SelectedPersistedDataKey; }
937 set { SelectedPersistedDataKey = value; }
940 [BindableAttribute (true)]
941 [DefaultValueAttribute (-1)]
942 public virtual int SelectedIndex {
944 return selectedIndex;
947 if (rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
948 int oldIndex = selectedIndex;
950 Rows [oldIndex].RowState = GetRowState (oldIndex);
952 selectedIndex = value;
953 if (rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
954 Rows [selectedIndex].RowState = GetRowState (selectedIndex);
959 [BrowsableAttribute (false)]
960 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
961 public virtual GridViewRow SelectedRow {
963 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
964 return Rows [selectedIndex];
970 [WebCategoryAttribute ("Styles")]
971 [PersistenceMode (PersistenceMode.InnerProperty)]
972 [NotifyParentProperty (true)]
973 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
974 public TableItemStyle SelectedRowStyle {
976 if (selectedRowStyle == null) {
977 selectedRowStyle = new TableItemStyle ();
978 if (IsTrackingViewState)
979 selectedRowStyle.TrackViewState();
981 return selectedRowStyle;
985 [BrowsableAttribute (false)]
986 public object SelectedValue {
988 if (SelectedDataKey != null)
989 return SelectedDataKey.Value;
995 [WebCategoryAttribute ("Appearance")]
996 [DefaultValueAttribute (false)]
997 public virtual bool ShowFooter {
999 object ob = ViewState ["ShowFooter"];
1000 if (ob != null) return (bool) ob;
1004 if (value == ShowFooter)
1006 ViewState ["ShowFooter"] = value;
1011 [WebCategoryAttribute ("Appearance")]
1012 [DefaultValueAttribute (true)]
1013 public virtual bool ShowHeader {
1015 object ob = ViewState ["ShowHeader"];
1016 if (ob != null) return (bool) ob;
1020 if (value == ShowHeader)
1022 ViewState ["ShowHeader"] = value;
1027 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
1028 [BrowsableAttribute (false)]
1029 [DefaultValueAttribute (SortDirection.Ascending)]
1030 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1031 public virtual SortDirection SortDirection {
1032 get { return sortDirection; }
1034 if (sortDirection == value)
1036 sortDirection = value;
1041 [BrowsableAttribute (false)]
1042 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1043 public virtual string SortExpression {
1045 if (sortExpression == null)
1046 return String.Empty;
1047 return sortExpression;
1050 if (sortExpression == value)
1052 sortExpression = value;
1057 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1058 [BrowsableAttribute (false)]
1059 public virtual GridViewRow TopPagerRow {
1066 [WebCategoryAttribute ("Accessibility")]
1067 [DefaultValueAttribute (true)]
1068 public virtual bool UseAccessibleHeader {
1070 object ob = ViewState ["UseAccessibleHeader"];
1071 if (ob != null) return (bool) ob;
1075 if (value == UseAccessibleHeader)
1077 ViewState ["UseAccessibleHeader"] = value;
1082 public virtual bool IsBindableType (Type type)
1084 return type.IsPrimitive || type == typeof (string) || type == typeof (decimal) || type == typeof (DateTime) || type == typeof (Guid);
1087 // MSDN: The CreateDataSourceSelectArguments method is a helper method called by
1088 // the GridView control to create the DataSourceSelectArguments object that
1089 // contains the arguments passed to the data source. In this implementation,
1090 // the DataSourceSelectArguments object contains the arguments for paging operations.
1091 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
1093 DataSourceSelectArguments arg = DataSourceSelectArguments.Empty;
1094 DataSourceView view= GetData();
1095 if (AllowPaging && view.CanPage) {
1096 arg.StartRowIndex = PageIndex * PageSize;
1097 if (view.CanRetrieveTotalRowCount) {
1098 arg.RetrieveTotalRowCount = true;
1099 arg.MaximumRows = PageSize;
1102 arg.MaximumRows = -1;
1106 if (IsBoundUsingDataSourceID && !String.IsNullOrEmpty (sortExpression)) {
1107 if (sortDirection == SortDirection.Ascending)
1108 arg.SortExpression = sortExpression;
1110 arg.SortExpression = sortExpression + " DESC";
1116 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
1118 bool autoGenerate = AutoGenerateColumns;
1121 IAutoFieldGenerator fieldGenerator = ColumnsGenerator;
1122 if (fieldGenerator != null)
1123 return fieldGenerator.GenerateFields (this);
1126 ArrayList fields = new ArrayList ();
1128 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
1129 CommandField field = new CommandField ();
1130 field.ShowEditButton = AutoGenerateEditButton;
1131 field.ShowDeleteButton = AutoGenerateDeleteButton;
1132 field.ShowSelectButton = AutoGenerateSelectButton;
1136 fields.AddRange (Columns);
1140 autoFieldProperties = CreateAutoFieldProperties (dataSource);
1142 if (autoFieldProperties != null) {
1143 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
1144 fields.Add (CreateAutoGeneratedColumn (props));
1151 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
1153 return new AutoGeneratedField (fieldProperties);
1156 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
1158 if(source == null) return null;
1160 PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
1163 ArrayList retVal = new ArrayList();
1167 object fitem = null;
1169 PropertyInfo prop_item = source.DataSource.GetType().GetProperty("Item",
1170 BindingFlags.Instance | BindingFlags.Static |
1171 BindingFlags.Public, null, null,
1172 new Type[] { typeof(int) }, null);
1174 if (prop_item != null) {
1175 prop_type = prop_item.PropertyType;
1178 if (prop_type == null || prop_type == typeof(object)) {
1179 IEnumerator en = source.GetEnumerator();
1180 if (en != null && en.MoveNext ()) {
1182 _dataEnumerator = en;
1185 prop_type = fitem.GetType();
1188 if (fitem != null && fitem is ICustomTypeDescriptor) {
1189 props = TypeDescriptor.GetProperties(fitem);
1190 } else if (prop_type != null) {
1191 if (IsBindableType (prop_type)) {
1192 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1193 ((IStateManager)field).TrackViewState();
1194 field.Name = "Item";
1195 field.DataField = BoundField.ThisExpression;
1196 field.Type = prop_type;
1199 props = TypeDescriptor.GetProperties (prop_type);
1204 if (props != null && props.Count > 0)
1206 foreach (PropertyDescriptor current in props) {
1207 if (IsBindableType (current.PropertyType)) {
1208 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1209 ((IStateManager)field).TrackViewState();
1210 field.Name = current.Name;
1211 field.DataField = current.Name;
1212 for (int i = 0; i < DataKeyNames.Length; i++) {
1213 if (string.Compare (DataKeyNames [i], current.Name, StringComparison.InvariantCultureIgnoreCase) == 0) {
1214 field.IsReadOnly = true;
1218 field.Type = current.PropertyType;
1224 if (retVal.Count > 0)
1225 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1227 return new AutoGeneratedFieldProperties [0];
1230 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1232 GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1236 void RequireBinding ()
1239 RequiresDataBinding = true;
1243 protected virtual Table CreateChildTable ()
1245 return new ContainedTable (this);
1248 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1259 PagedDataSource dataSource;
1262 DataSourceView view = GetData ();
1263 dataSource = new PagedDataSource ();
1264 dataSource.DataSource = data;
1267 dataSource.AllowPaging = true;
1268 dataSource.PageSize = PageSize;
1270 dataSource.AllowServerPaging = true;
1271 if (SelectArguments.RetrieveTotalRowCount)
1272 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1274 if (PageIndex >= dataSource.PageCount)
1275 pageIndex = dataSource.PageCount - 1;
1276 dataSource.CurrentPageIndex = PageIndex;
1279 PageCount = dataSource.PageCount;
1283 dataSource = new PagedDataSource ();
1284 dataSource.DataSource = data;
1286 dataSource.AllowPaging = true;
1287 dataSource.PageSize = PageSize;
1288 dataSource.CurrentPageIndex = PageIndex;
1292 bool createPager = AllowPaging && (PageCount >= 1) && PagerSettings.Visible;
1294 ArrayList list = new ArrayList ();
1296 // Creates the set of fields to show
1298 _dataEnumerator = null;
1299 ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1300 int fieldCount = fieldCollection.Count;
1301 DataControlField dcf;
1302 DataControlField[] fields = new DataControlField [fieldCount];
1303 fieldCollection.CopyTo (fields, 0);
1305 for (int i = 0; i < fieldCount; i++) {
1307 dcf.Initialize (AllowSorting, this);
1308 if (EnableSortingAndPagingCallbacks)
1309 dcf.ValidateSupportsCallback ();
1312 bool skip_first = false;
1313 IEnumerator enumerator;
1314 if (_dataEnumerator != null) {
1315 // replaced when creating bound columns
1316 enumerator = _dataEnumerator;
1320 enumerator = dataSource.GetEnumerator ();
1323 // Main table creation
1324 Table mainTable = ContainedTable;
1325 while (skip_first || enumerator.MoveNext ()) {
1327 object obj = enumerator.Current;
1329 if (list.Count == 0) {
1330 if (createPager && (PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom)) {
1331 topPagerRow = CreatePagerRow (fieldCount, dataSource);
1332 OnRowCreated (new GridViewRowEventArgs (topPagerRow));
1333 mainTable.Rows.Add (topPagerRow);
1335 topPagerRow.DataBind ();
1336 OnRowDataBound (new GridViewRowEventArgs (topPagerRow));
1339 topPagerRow.Visible = false;
1342 GridViewRow headerRow = CreateRow (-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
1343 InitializeRow (headerRow, fields);
1344 OnRowCreated (new GridViewRowEventArgs (headerRow));
1345 mainTable.Rows.Add (headerRow);
1347 headerRow.DataBind ();
1348 OnRowDataBound (new GridViewRowEventArgs (headerRow));
1352 DataControlRowState rstate = GetRowState (list.Count);
1353 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1356 InitializeRow (row, fields);
1357 OnRowCreated (new GridViewRowEventArgs (row));
1358 mainTable.Rows.Add (row);
1361 if (EditIndex == row.RowIndex)
1362 oldEditValues = new DataKey (GetRowValues (row, true, true));
1363 DataKeyArrayList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1364 OnRowDataBound (new GridViewRowEventArgs (row));
1368 if (list.Count == 0) {
1369 GridViewRow emptyRow = CreateEmptyrRow (fieldCount);
1370 if (emptyRow != null) {
1371 OnRowCreated (new GridViewRowEventArgs (emptyRow));
1372 mainTable.Rows.Add (emptyRow);
1374 emptyRow.DataBind ();
1375 OnRowDataBound (new GridViewRowEventArgs (emptyRow));
1381 GridViewRow footerRow = CreateRow (-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
1382 InitializeRow (footerRow, fields);
1383 OnRowCreated (new GridViewRowEventArgs (footerRow));
1384 mainTable.Rows.Add (footerRow);
1386 footerRow.DataBind ();
1387 OnRowDataBound (new GridViewRowEventArgs (footerRow));
1390 if (createPager && (PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom)) {
1391 bottomPagerRow = CreatePagerRow (fieldCount, dataSource);
1392 OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
1393 mainTable.Rows.Add (bottomPagerRow);
1395 bottomPagerRow.DataBind ();
1396 OnRowDataBound (new GridViewRowEventArgs (bottomPagerRow));
1399 bottomPagerRow.Visible = false;
1403 rows = new GridViewRowCollection (list);
1409 return dataSource.DataSourceCount;
1414 Table ContainedTable {
1416 if (table == null) {
1417 table = CreateChildTable ();
1418 Controls.Add (table);
1424 protected override Style CreateControlStyle ()
1426 TableStyle style = new TableStyle (ViewState);
1427 style.GridLines = GridLines.Both;
1428 style.CellSpacing = 0;
1432 DataControlRowState GetRowState (int index)
1434 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1435 if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1436 if (index == EditIndex) rstate |= DataControlRowState.Edit;
1440 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1442 GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1443 InitializePager (row, fieldCount, dataSource);
1447 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1449 TableCell cell = new TableCell ();
1451 cell.ColumnSpan = columnSpan;
1453 if (pagerTemplate != null)
1454 pagerTemplate.InstantiateIn (cell);
1456 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1458 row.Cells.Add (cell);
1461 GridViewRow CreateEmptyrRow (int fieldCount)
1463 if (emptyDataTemplate == null && String.IsNullOrEmpty (EmptyDataText))
1466 GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1467 TableCell cell = new TableCell ();
1468 cell.ColumnSpan = fieldCount;
1470 if (emptyDataTemplate != null)
1471 emptyDataTemplate.InstantiateIn (cell);
1473 cell.Text = EmptyDataText;
1475 row.Cells.Add (cell);
1479 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1481 DataControlCellType ctype;
1482 bool accessibleHeader = false;
1484 switch (row.RowType) {
1485 case DataControlRowType.Header:
1486 ctype = DataControlCellType.Header;
1487 accessibleHeader = UseAccessibleHeader;
1489 case DataControlRowType.Footer:
1490 ctype = DataControlCellType.Footer;
1493 ctype = DataControlCellType.DataCell;
1497 for (int n=0; n<fields.Length; n++) {
1498 DataControlField field = fields [n];
1500 DataControlFieldCell cell;
1501 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1502 cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1504 cell = new DataControlFieldCell (field);
1505 row.Cells.Add (cell);
1506 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1510 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1512 if (cachedKeyProperties == null) {
1513 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1514 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1515 for (int n=0; n<DataKeyNames.Length; n++) {
1516 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1518 throw new InvalidOperationException ("Property '" + DataKeyNames [n] + "' not found in object of type " + row.DataItem.GetType ());
1519 cachedKeyProperties [n] = p;
1523 OrderedDictionary dic = new OrderedDictionary ();
1524 foreach (PropertyDescriptor p in cachedKeyProperties)
1525 dic [p.Name] = p.GetValue (row.DataItem);
1529 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1531 OrderedDictionary dic = new OrderedDictionary ();
1532 ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1536 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1538 DataControlField field;
1539 foreach (TableCell cell in row.Cells) {
1540 DataControlFieldCell c = cell as DataControlFieldCell;
1544 field = c.ContainingField;
1545 if (field != null && !field.Visible)
1548 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1550 if (!includePrimaryKey && DataKeyNames != null)
1551 foreach (string key in DataKeyNames)
1552 fieldValues.Remove (key);
1555 protected override HtmlTextWriterTag TagKey {
1557 if (EnableSortingAndPagingCallbacks)
1558 return HtmlTextWriterTag.Div;
1560 return HtmlTextWriterTag.Table;
1564 public sealed override void DataBind ()
1566 DataKeyArrayList.Clear ();
1567 cachedKeyProperties = null;
1570 keys = new DataKeyArray (DataKeyArrayList);
1572 GridViewRow row = HeaderRow;
1574 row.Visible = ShowHeader;
1578 row.Visible = ShowFooter;
1581 protected internal override void PerformDataBinding (IEnumerable data)
1583 base.PerformDataBinding (data);
1586 protected internal virtual void PrepareControlHierarchy ()
1591 table.Caption = Caption;
1592 table.CaptionAlign = CaptionAlign;
1593 table.CopyBaseAttributes (this);
1595 foreach (GridViewRow row in table.Rows) {
1596 switch (row.RowType) {
1597 case DataControlRowType.Header:
1598 if (headerStyle != null && !headerStyle.IsEmpty)
1599 row.ControlStyle.MergeWith(headerStyle);
1600 row.Visible = ShowHeader;
1602 case DataControlRowType.Footer:
1603 if (footerStyle != null && !footerStyle.IsEmpty)
1604 row.ControlStyle.MergeWith (footerStyle);
1605 row.Visible = ShowFooter;
1607 case DataControlRowType.Pager:
1608 if (pagerStyle != null && !pagerStyle.IsEmpty)
1609 row.ControlStyle.MergeWith (pagerStyle);
1611 case DataControlRowType.EmptyDataRow:
1612 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1613 row.ControlStyle.MergeWith (emptyDataRowStyle);
1615 case DataControlRowType.DataRow:
1616 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1617 row.ControlStyle.MergeWith (editRowStyle);
1618 if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null && !selectedRowStyle.IsEmpty)
1619 row.ControlStyle.MergeWith (selectedRowStyle);
1620 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1621 row.ControlStyle.MergeWith (alternatingRowStyle);
1622 if (rowStyle != null && !rowStyle.IsEmpty)
1623 row.ControlStyle.MergeWith (rowStyle);
1629 foreach (TableCell cell in row.Cells) {
1630 DataControlFieldCell fcell = cell as DataControlFieldCell;
1631 if (fcell != null) {
1632 DataControlField field = fcell.ContainingField;
1635 if (!field.Visible) {
1636 cell.Visible = false;
1640 switch (row.RowType) {
1641 case DataControlRowType.Header:
1642 if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1643 cell.ControlStyle.MergeWith (field.HeaderStyle);
1645 case DataControlRowType.Footer:
1646 if (field.FooterStyleCreated && !field.FooterStyle.IsEmpty)
1647 cell.ControlStyle.MergeWith (field.FooterStyle);
1650 if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1651 foreach (Control c in cell.Controls) {
1652 WebControl wc = c as WebControl;
1654 wc.ControlStyle.MergeWith (field.ControlStyle);
1656 if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1657 cell.ControlStyle.MergeWith (field.ItemStyle);
1665 protected internal override void OnInit (EventArgs e)
1667 Page.RegisterRequiresControlState (this);
1671 void OnFieldsChanged (object sender, EventArgs args)
1676 protected override void OnDataPropertyChanged ()
1678 base.OnDataPropertyChanged ();
1682 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1684 base.OnDataSourceViewChanged (sender, e);
1688 protected override bool OnBubbleEvent (object source, EventArgs e)
1690 GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1692 bool causesValidation = false;
1693 IButtonControl button = args.CommandSource as IButtonControl;
1694 if (button != null && button.CausesValidation) {
1695 Page.Validate (button.ValidationGroup);
1696 causesValidation = true;
1698 OnRowCommand (args);
1699 string param = args.CommandArgument as string;
1700 if (param == null || param.Length == 0) {
1701 GridViewRow row = args.Row;
1703 param = row.RowIndex.ToString();
1705 ProcessEvent (args.CommandName, param, causesValidation);
1708 return base.OnBubbleEvent (source, e);
1711 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1713 ValidateEvent (UniqueID, eventArgument);
1714 RaisePostBackEvent (eventArgument);
1717 // This is prolly obsolete
1718 protected virtual void RaisePostBackEvent (string eventArgument)
1720 GridViewCommandEventArgs args;
1721 int i = eventArgument.IndexOf ('$');
1723 args = new GridViewCommandEventArgs (this, new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1)));
1725 args = new GridViewCommandEventArgs (this, new CommandEventArgs (eventArgument, null));
1727 OnRowCommand (args);
1728 ProcessEvent (args.CommandName, (string) args.CommandArgument, false);
1731 void ProcessEvent (string eventName, string param, bool causesValidation)
1735 case DataControlCommands.PageCommandName:
1738 case DataControlCommands.FirstPageCommandArgument:
1741 case DataControlCommands.LastPageCommandArgument:
1742 newIndex = PageCount - 1;
1744 case DataControlCommands.NextPageCommandArgument:
1745 newIndex = PageIndex + 1;
1747 case DataControlCommands.PreviousPageCommandArgument:
1748 newIndex = PageIndex - 1;
1752 int.TryParse (param, out paramIndex);
1753 newIndex = paramIndex - 1;
1756 ShowPage (newIndex);
1759 case DataControlCommands.FirstPageCommandArgument:
1763 case DataControlCommands.LastPageCommandArgument:
1764 ShowPage (PageCount - 1);
1767 case DataControlCommands.NextPageCommandArgument:
1768 if (PageIndex < PageCount - 1)
1769 ShowPage (PageIndex + 1);
1772 case DataControlCommands.PreviousPageCommandArgument:
1774 ShowPage (PageIndex - 1);
1777 case DataControlCommands.SelectCommandName:
1778 SelectRow (int.Parse (param));
1781 case DataControlCommands.EditCommandName:
1782 EditRow (int.Parse (param));
1785 case DataControlCommands.UpdateCommandName:
1786 int editIndex = int.Parse (param);
1787 UpdateRow (Rows [editIndex], editIndex, causesValidation);
1790 case DataControlCommands.CancelCommandName:
1794 case DataControlCommands.DeleteCommandName:
1795 DeleteRow (int.Parse (param));
1798 case DataControlCommands.SortCommandName:
1804 void Sort (string newSortExpression)
1806 SortDirection newDirection = SortDirection.Ascending;
1807 if (sortExpression == newSortExpression && sortDirection == SortDirection.Ascending)
1808 newDirection = SortDirection.Descending;
1810 Sort (newSortExpression, newDirection);
1813 public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
1815 GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1817 if (args.Cancel) return;
1819 if (IsBoundUsingDataSourceID) {
1822 SortExpression = args.SortExpression;
1823 SortDirection = args.SortDirection;
1826 OnSorted (EventArgs.Empty);
1829 void SelectRow (int index)
1831 GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1832 OnSelectedIndexChanging (args);
1835 SelectedIndex = args.NewSelectedIndex;
1836 OnSelectedIndexChanged (EventArgs.Empty);
1840 void ShowPage (int newIndex)
1842 GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1843 OnPageIndexChanging (args);
1845 if (args.Cancel || !IsBoundUsingDataSourceID)
1849 PageIndex = args.NewPageIndex;
1850 OnPageIndexChanged (EventArgs.Empty);
1853 void EditRow (int index)
1855 GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1856 OnRowEditing (args);
1858 if (args.Cancel || !IsBoundUsingDataSourceID)
1861 EditIndex = args.NewEditIndex;
1866 GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1867 OnRowCancelingEdit (args);
1869 if (args.Cancel || !IsBoundUsingDataSourceID)
1875 [MonoTODO ("Support two-way binding expressions")]
1876 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1878 if (rowIndex != EditIndex) throw new NotSupportedException ();
1880 GridViewRow row = Rows [rowIndex];
1881 UpdateRow (row, rowIndex, causesValidation);
1884 void UpdateRow (GridViewRow row, int rowIndex, bool causesValidation)
1886 if (causesValidation && Page != null && !Page.IsValid)
1889 currentEditOldValues = CopyOrderedDictionary (OldEditValues.Values);
1890 currentEditRowKeys = CopyOrderedDictionary (DataKeys [rowIndex].Values);
1891 currentEditNewValues = GetRowValues (row, false, false);
1893 GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (rowIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1894 OnRowUpdating (args);
1896 if (args.Cancel || !IsBoundUsingDataSourceID)
1899 DataSourceView view = GetData ();
1901 throw new HttpException ("The DataSourceView associated to data bound control was null");
1902 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1905 static IOrderedDictionary CopyOrderedDictionary (IOrderedDictionary sourceDic) {
1906 OrderedDictionary copyDic = new OrderedDictionary ();
1907 foreach (object key in sourceDic.Keys) {
1908 copyDic.Add (key, sourceDic [key]);
1913 bool UpdateCallback (int recordsAffected, Exception exception)
1915 GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1916 OnRowUpdated (dargs);
1918 if (!dargs.KeepInEditMode)
1921 return dargs.ExceptionHandled;
1924 public virtual void DeleteRow (int rowIndex)
1926 GridViewRow row = Rows [rowIndex];
1927 currentEditRowKeys = CopyOrderedDictionary (DataKeys [rowIndex].Values);
1928 currentEditNewValues = GetRowValues (row, true, true);
1930 GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1931 OnRowDeleting (args);
1933 if (args.Cancel || !IsBoundUsingDataSourceID)
1937 DataSourceView view = GetData ();
1939 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1941 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1942 OnRowDeleted (dargs);
1946 bool DeleteCallback (int recordsAffected, Exception exception)
1948 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1949 OnRowDeleted (dargs);
1950 return dargs.ExceptionHandled;
1956 oldEditValues = new DataKey (new OrderedDictionary ());
1957 currentEditRowKeys = null;
1958 currentEditOldValues = null;
1959 currentEditNewValues = null;
1962 protected internal override void LoadControlState (object ob)
1964 if (ob == null) return;
1965 object[] state = (object[]) ob;
1966 base.LoadControlState (state[0]);
1967 pageIndex = (int) state[1];
1968 selectedIndex = (int) state[2];
1969 editIndex = (int) state[3];
1970 sortExpression = (string) state[4];
1971 sortDirection = (SortDirection) state[5];
1972 DataKeyNames = (string []) state [6];
1973 if (state [7] != null)
1974 LoadDataKeyArrayState ((object []) state [7]);
1975 if (state [8] != null)
1976 ((IStateManager) OldEditValues).LoadViewState (state [8]);
1979 protected internal override object SaveControlState ()
1981 if (EnableSortingAndPagingCallbacks) {
1982 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1983 Page.ClientScript.RegisterHiddenField (ClientID + "_SortExpression", SortExpression);
1984 Page.ClientScript.RegisterHiddenField (ClientID + "_SortDirection", ((int)SortDirection).ToString());
1987 object bstate = base.SaveControlState ();
1988 return new object [] {
1996 SaveDataKeyArrayState (),
1997 (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState ())
2001 object [] SaveDataKeyArrayState ()
2006 object [] state = new object [keys.Count];
2007 for (int i = 0; i < keys.Count; i++) {
2008 state [i] = ((IStateManager) keys [i]).SaveViewState ();
2013 void LoadDataKeyArrayState (object [] state)
2015 for (int i = 0; i < state.Length; i++) {
2016 DataKey dataKey = new DataKey (new OrderedDictionary (DataKeyNames.Length), DataKeyNames);
2017 ((IStateManager) dataKey).LoadViewState (state [i]);
2018 DataKeyArrayList.Add (dataKey);
2020 keys = new DataKeyArray (DataKeyArrayList);
2023 protected override void TrackViewState()
2025 base.TrackViewState();
2026 if (columns != null) ((IStateManager)columns).TrackViewState();
2027 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
2028 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
2029 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
2030 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
2031 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
2032 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
2033 if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
2034 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
2035 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
2036 if (keys != null) ((IStateManager)keys).TrackViewState();
2037 if (autoFieldProperties != null) {
2038 foreach (IStateManager sm in autoFieldProperties)
2039 sm.TrackViewState ();
2043 protected override object SaveViewState()
2045 object[] states = new object [12];
2046 states[0] = base.SaveViewState();
2047 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
2048 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
2049 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
2050 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
2051 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
2052 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
2053 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
2054 states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
2055 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
2056 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
2058 if (autoFieldProperties != null) {
2059 object[] data = new object [autoFieldProperties.Length];
2060 bool allNull = true;
2061 for (int n=0; n<data.Length; n++) {
2062 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
2063 if (data [n] != null) allNull = false;
2065 if (!allNull) states [11] = data;
2068 for (int i = states.Length - 1; i >= 0; i--) {
2069 if (states [i] != null)
2076 protected override void LoadViewState (object savedState)
2078 if (savedState == null) {
2079 base.LoadViewState (null);
2083 object [] states = (object []) savedState;
2085 if (states[11] != null) {
2086 object[] data = (object[]) states [11];
2087 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
2088 for (int n=0; n<data.Length; n++) {
2089 IStateManager p = new AutoGeneratedFieldProperties ();
2090 p.TrackViewState ();
2091 p.LoadViewState (data [n]);
2092 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
2096 base.LoadViewState (states[0]);
2098 if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
2099 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
2100 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
2101 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
2102 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
2103 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
2104 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
2105 if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
2106 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
2107 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
2110 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
2112 RaiseCallbackEvent (eventArgs);
2115 protected virtual void RaiseCallbackEvent (string eventArgs)
2117 string[] clientData = eventArgs.Split ('|');
2118 PageIndex = int.Parse (clientData[0]);
2119 SortExpression = HttpUtility.UrlDecode (clientData [1]);
2120 SortDirection = (SortDirection) int.Parse (clientData [2]);
2122 RaisePostBackEvent (clientData[3]);
2126 string ICallbackEventHandler.GetCallbackResult ()
2128 return GetCallbackResult ();
2131 protected virtual string GetCallbackResult ()
2133 PrepareControlHierarchy ();
2135 StringWriter sw = new StringWriter ();
2136 sw.Write (PageIndex.ToString () + '|' + SortExpression + '|' + (int) SortDirection + '|');
2138 HtmlTextWriter writer = new HtmlTextWriter (sw);
2139 RenderGrid (writer);
2140 return sw.ToString ();
2143 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
2145 return GetCallbackScript (control, argument);
2148 protected virtual string GetCallbackScript (IButtonControl control, string argument)
2150 if (EnableSortingAndPagingCallbacks) {
2153 page.ClientScript.RegisterForEventValidation (UniqueID, argument);
2154 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
2159 protected override void OnPagePreLoad (object sender, EventArgs e)
2161 base.OnPagePreLoad (sender, e);
2163 if (Page.IsPostBack && EnableSortingAndPagingCallbacks) {
2165 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
2168 if (int.TryParse (Page.Request.Form [ClientID + "_SortDirection"], out dir))
2169 SortDirection = (SortDirection) dir;
2170 SortExpression = Page.Request.Form [ClientID + "_SortExpression"];
2175 const string onPreRenderScript = @"var {0} = new Object ();
2176 {0}.pageIndex = {1};
2182 protected internal override void OnPreRender (EventArgs e)
2184 base.OnPreRender (e);
2186 if (EnableSortingAndPagingCallbacks) {
2187 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
2188 string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
2189 Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
2192 string cgrid = ClientID + "_data";
2193 string script = String.Format (onPreRenderScript,
2195 ClientScriptManager.GetScriptLiteral (PageIndex),
2196 ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression),
2197 ClientScriptManager.GetScriptLiteral ((int) SortDirection),
2198 ClientScriptManager.GetScriptLiteral (UniqueID),
2201 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
2203 // Make sure the basic script infrastructure is rendered
2204 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
2205 Page.ClientScript.GetPostBackClientHyperlink (this, "");
2209 protected internal override void Render (HtmlTextWriter writer)
2211 PrepareControlHierarchy ();
2212 if (EnableSortingAndPagingCallbacks)
2213 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_div");
2214 writer.RenderBeginTag (HtmlTextWriterTag.Div);
2216 RenderGrid (writer);
2218 writer.RenderEndTag ();
2221 void RenderGrid (HtmlTextWriter writer)
2226 table.Render (writer);
2229 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
2231 if (control == null)
2232 throw new ArgumentNullException ("control");
2234 if (control.CausesValidation)
2235 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.");
2237 PostBackOptions options = new PostBackOptions (this);
2238 options.Argument = control.CommandName + "$" + control.CommandArgument;
2239 options.RequiresJavaScriptProtocol = true;