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 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];
928 [BindableAttribute (true)]
929 [DefaultValueAttribute (-1)]
930 public virtual int SelectedIndex {
932 return selectedIndex;
935 if (rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
936 int oldIndex = selectedIndex;
938 Rows [oldIndex].RowState = GetRowState (oldIndex);
940 selectedIndex = value;
941 if (rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
942 Rows [selectedIndex].RowState = GetRowState (selectedIndex);
947 [BrowsableAttribute (false)]
948 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
949 public virtual GridViewRow SelectedRow {
951 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
952 return Rows [selectedIndex];
958 [WebCategoryAttribute ("Styles")]
959 [PersistenceMode (PersistenceMode.InnerProperty)]
960 [NotifyParentProperty (true)]
961 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
962 public TableItemStyle SelectedRowStyle {
964 if (selectedRowStyle == null) {
965 selectedRowStyle = new TableItemStyle ();
966 if (IsTrackingViewState)
967 selectedRowStyle.TrackViewState();
969 return selectedRowStyle;
973 [BrowsableAttribute (false)]
974 public object SelectedValue {
976 if (SelectedDataKey != null)
977 return SelectedDataKey.Value;
983 [WebCategoryAttribute ("Appearance")]
984 [DefaultValueAttribute (false)]
985 public virtual bool ShowFooter {
987 object ob = ViewState ["ShowFooter"];
988 if (ob != null) return (bool) ob;
992 if (value == ShowFooter)
994 ViewState ["ShowFooter"] = value;
999 [WebCategoryAttribute ("Appearance")]
1000 [DefaultValueAttribute (true)]
1001 public virtual bool ShowHeader {
1003 object ob = ViewState ["ShowHeader"];
1004 if (ob != null) return (bool) ob;
1008 if (value == ShowHeader)
1010 ViewState ["ShowHeader"] = value;
1015 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
1016 [BrowsableAttribute (false)]
1017 [DefaultValueAttribute (SortDirection.Ascending)]
1018 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1019 public virtual SortDirection SortDirection {
1020 get { return sortDirection; }
1022 if (sortDirection == value)
1024 sortDirection = value;
1029 [BrowsableAttribute (false)]
1030 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1031 public virtual string SortExpression {
1033 if (sortExpression == null)
1034 return String.Empty;
1035 return sortExpression;
1038 if (sortExpression == value)
1040 sortExpression = value;
1045 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
1046 [BrowsableAttribute (false)]
1047 public virtual GridViewRow TopPagerRow {
1054 [WebCategoryAttribute ("Accessibility")]
1055 [DefaultValueAttribute (true)]
1056 public virtual bool UseAccessibleHeader {
1058 object ob = ViewState ["UseAccessibleHeader"];
1059 if (ob != null) return (bool) ob;
1063 if (value == UseAccessibleHeader)
1065 ViewState ["UseAccessibleHeader"] = value;
1070 public virtual bool IsBindableType (Type type)
1072 return type.IsPrimitive || type == typeof (string) || type == typeof (decimal) || type == typeof (DateTime) || type == typeof (Guid);
1075 // MSDN: The CreateDataSourceSelectArguments method is a helper method called by
1076 // the GridView control to create the DataSourceSelectArguments object that
1077 // contains the arguments passed to the data source. In this implementation,
1078 // the DataSourceSelectArguments object contains the arguments for paging operations.
1079 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
1081 DataSourceSelectArguments arg = DataSourceSelectArguments.Empty;
1082 DataSourceView view= GetData();
1083 if (AllowPaging && view.CanPage) {
1084 arg.StartRowIndex = PageIndex * PageSize;
1085 if (view.CanRetrieveTotalRowCount) {
1086 arg.RetrieveTotalRowCount = true;
1087 arg.MaximumRows = PageSize;
1090 arg.MaximumRows = -1;
1094 if (IsBoundUsingDataSourceID && !String.IsNullOrEmpty (sortExpression)) {
1095 if (sortDirection == SortDirection.Ascending)
1096 arg.SortExpression = sortExpression;
1098 arg.SortExpression = sortExpression + " DESC";
1104 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
1106 bool autoGenerate = AutoGenerateColumns;
1109 IAutoFieldGenerator fieldGenerator = ColumnsGenerator;
1110 if (fieldGenerator != null)
1111 return fieldGenerator.GenerateFields (this);
1114 ArrayList fields = new ArrayList ();
1116 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
1117 CommandField field = new CommandField ();
1118 field.ShowEditButton = AutoGenerateEditButton;
1119 field.ShowDeleteButton = AutoGenerateDeleteButton;
1120 field.ShowSelectButton = AutoGenerateSelectButton;
1124 fields.AddRange (Columns);
1128 autoFieldProperties = CreateAutoFieldProperties (dataSource);
1130 if (autoFieldProperties != null) {
1131 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
1132 fields.Add (CreateAutoGeneratedColumn (props));
1139 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
1141 return new AutoGeneratedField (fieldProperties);
1144 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
1146 if(source == null) return null;
1148 PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
1151 ArrayList retVal = new ArrayList();
1155 object fitem = null;
1157 PropertyInfo prop_item = source.DataSource.GetType().GetProperty("Item",
1158 BindingFlags.Instance | BindingFlags.Static |
1159 BindingFlags.Public, null, null,
1160 new Type[] { typeof(int) }, null);
1162 if (prop_item != null) {
1163 prop_type = prop_item.PropertyType;
1166 if (prop_type == null || prop_type == typeof(object)) {
1167 IEnumerator en = source.GetEnumerator();
1168 if (en != null && en.MoveNext ()) {
1170 _dataEnumerator = en;
1173 prop_type = fitem.GetType();
1176 if (fitem != null && fitem is ICustomTypeDescriptor) {
1177 props = TypeDescriptor.GetProperties(fitem);
1178 } else if (prop_type != null) {
1179 if (IsBindableType (prop_type)) {
1180 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1181 ((IStateManager)field).TrackViewState();
1182 field.Name = "Item";
1183 field.DataField = BoundField.ThisExpression;
1184 field.Type = prop_type;
1187 props = TypeDescriptor.GetProperties (prop_type);
1192 if (props != null && props.Count > 0)
1194 foreach (PropertyDescriptor current in props) {
1195 if (IsBindableType (current.PropertyType)) {
1196 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1197 ((IStateManager)field).TrackViewState();
1198 field.Name = current.Name;
1199 field.DataField = current.Name;
1200 for (int i = 0; i < DataKeyNames.Length; i++) {
1201 if (string.Compare (DataKeyNames [i], current.Name, StringComparison.InvariantCultureIgnoreCase) == 0) {
1202 field.IsReadOnly = true;
1206 field.Type = current.PropertyType;
1212 if (retVal.Count > 0)
1213 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1215 return new AutoGeneratedFieldProperties [0];
1218 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1220 GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1224 void RequireBinding ()
1227 RequiresDataBinding = true;
1231 protected virtual Table CreateChildTable ()
1233 return new ContainedTable (this);
1236 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1247 PagedDataSource dataSource;
1250 DataSourceView view = GetData ();
1251 dataSource = new PagedDataSource ();
1252 dataSource.DataSource = data;
1255 dataSource.AllowPaging = true;
1256 dataSource.PageSize = PageSize;
1258 dataSource.AllowServerPaging = true;
1259 if (SelectArguments.RetrieveTotalRowCount)
1260 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1262 if (PageIndex >= dataSource.PageCount)
1263 pageIndex = dataSource.PageCount - 1;
1264 dataSource.CurrentPageIndex = PageIndex;
1267 PageCount = dataSource.PageCount;
1271 dataSource = new PagedDataSource ();
1272 dataSource.DataSource = data;
1274 dataSource.AllowPaging = true;
1275 dataSource.PageSize = PageSize;
1276 dataSource.CurrentPageIndex = PageIndex;
1280 bool createPager = AllowPaging && (PageCount >= 1) && PagerSettings.Visible;
1282 ArrayList list = new ArrayList ();
1284 // Creates the set of fields to show
1286 _dataEnumerator = null;
1287 ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1288 int fieldCount = fieldCollection.Count;
1289 DataControlField dcf;
1290 DataControlField[] fields = new DataControlField [fieldCount];
1291 fieldCollection.CopyTo (fields, 0);
1293 for (int i = 0; i < fieldCount; i++) {
1295 dcf.Initialize (AllowSorting, this);
1296 if (EnableSortingAndPagingCallbacks)
1297 dcf.ValidateSupportsCallback ();
1300 bool skip_first = false;
1301 IEnumerator enumerator;
1302 if (_dataEnumerator != null) {
1303 // replaced when creating bound columns
1304 enumerator = _dataEnumerator;
1308 enumerator = dataSource.GetEnumerator ();
1311 // Main table creation
1312 while (skip_first || enumerator.MoveNext ()) {
1314 object obj = enumerator.Current;
1316 if (list.Count == 0) {
1317 if (createPager && (PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom)) {
1318 topPagerRow = CreatePagerRow (fieldCount, dataSource);
1319 OnRowCreated (new GridViewRowEventArgs (topPagerRow));
1320 ContainedTable.Rows.Add (topPagerRow);
1322 topPagerRow.DataBind ();
1323 OnRowDataBound (new GridViewRowEventArgs (topPagerRow));
1326 topPagerRow.Visible = false;
1329 GridViewRow headerRow = CreateRow (-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
1330 InitializeRow (headerRow, fields);
1331 OnRowCreated (new GridViewRowEventArgs (headerRow));
1332 ContainedTable.Rows.Add (headerRow);
1334 headerRow.DataBind ();
1335 OnRowDataBound (new GridViewRowEventArgs (headerRow));
1339 DataControlRowState rstate = GetRowState (list.Count);
1340 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1343 InitializeRow (row, fields);
1344 OnRowCreated (new GridViewRowEventArgs (row));
1345 ContainedTable.Rows.Add (row);
1348 if (EditIndex == row.RowIndex)
1349 oldEditValues = new DataKey (GetRowValues (row, true, true));
1350 DataKeyArrayList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1351 OnRowDataBound (new GridViewRowEventArgs (row));
1355 if (list.Count == 0) {
1356 GridViewRow emptyRow = CreateEmptyrRow (fieldCount);
1357 if (emptyRow != null) {
1358 OnRowCreated (new GridViewRowEventArgs (emptyRow));
1359 ContainedTable.Rows.Add (emptyRow);
1361 emptyRow.DataBind ();
1362 OnRowDataBound (new GridViewRowEventArgs (emptyRow));
1368 GridViewRow footerRow = CreateRow (-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
1369 InitializeRow (footerRow, fields);
1370 OnRowCreated (new GridViewRowEventArgs (footerRow));
1371 ContainedTable.Rows.Add (footerRow);
1373 footerRow.DataBind ();
1374 OnRowDataBound (new GridViewRowEventArgs (footerRow));
1377 if (createPager && (PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom)) {
1378 bottomPagerRow = CreatePagerRow (fieldCount, dataSource);
1379 OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
1380 ContainedTable.Rows.Add (bottomPagerRow);
1382 bottomPagerRow.DataBind ();
1383 OnRowDataBound (new GridViewRowEventArgs (bottomPagerRow));
1386 bottomPagerRow.Visible = false;
1390 rows = new GridViewRowCollection (list);
1396 return dataSource.DataSourceCount;
1401 Table ContainedTable {
1403 if (table == null) {
1404 table = CreateChildTable ();
1405 Controls.Add (table);
1411 protected override Style CreateControlStyle ()
1413 TableStyle style = new TableStyle (ViewState);
1414 style.GridLines = GridLines.Both;
1415 style.CellSpacing = 0;
1419 DataControlRowState GetRowState (int index)
1421 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1422 if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1423 if (index == EditIndex) rstate |= DataControlRowState.Edit;
1427 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1429 GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1430 InitializePager (row, fieldCount, dataSource);
1434 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1436 TableCell cell = new TableCell ();
1438 cell.ColumnSpan = columnSpan;
1440 if (pagerTemplate != null)
1441 pagerTemplate.InstantiateIn (cell);
1443 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1445 row.Cells.Add (cell);
1448 GridViewRow CreateEmptyrRow (int fieldCount)
1450 if (emptyDataTemplate == null && String.IsNullOrEmpty (EmptyDataText))
1453 GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1454 TableCell cell = new TableCell ();
1455 cell.ColumnSpan = fieldCount;
1457 if (emptyDataTemplate != null)
1458 emptyDataTemplate.InstantiateIn (cell);
1460 cell.Text = EmptyDataText;
1462 row.Cells.Add (cell);
1466 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1468 DataControlCellType ctype;
1469 bool accessibleHeader = false;
1471 switch (row.RowType) {
1472 case DataControlRowType.Header:
1473 ctype = DataControlCellType.Header;
1474 accessibleHeader = UseAccessibleHeader;
1476 case DataControlRowType.Footer:
1477 ctype = DataControlCellType.Footer;
1480 ctype = DataControlCellType.DataCell;
1484 for (int n=0; n<fields.Length; n++) {
1485 DataControlField field = fields [n];
1487 DataControlFieldCell cell;
1488 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1489 cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1491 cell = new DataControlFieldCell (field);
1492 row.Cells.Add (cell);
1493 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1497 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1499 if (cachedKeyProperties == null) {
1500 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1501 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1502 for (int n=0; n<DataKeyNames.Length; n++) {
1503 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1505 throw new InvalidOperationException ("Property '" + DataKeyNames [n] + "' not found in object of type " + row.DataItem.GetType ());
1506 cachedKeyProperties [n] = p;
1510 OrderedDictionary dic = new OrderedDictionary ();
1511 foreach (PropertyDescriptor p in cachedKeyProperties)
1512 dic [p.Name] = p.GetValue (row.DataItem);
1516 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1518 OrderedDictionary dic = new OrderedDictionary ();
1519 ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1523 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1525 DataControlField field;
1526 foreach (TableCell cell in row.Cells) {
1527 DataControlFieldCell c = cell as DataControlFieldCell;
1531 field = c.ContainingField;
1532 if (field != null && !field.Visible)
1535 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1537 if (!includePrimaryKey && DataKeyNames != null)
1538 foreach (string key in DataKeyNames)
1539 fieldValues.Remove (key);
1542 protected override HtmlTextWriterTag TagKey {
1544 if (EnableSortingAndPagingCallbacks)
1545 return HtmlTextWriterTag.Div;
1547 return HtmlTextWriterTag.Table;
1551 public sealed override void DataBind ()
1553 DataKeyArrayList.Clear ();
1554 cachedKeyProperties = null;
1557 keys = new DataKeyArray (DataKeyArrayList);
1560 protected internal override void PerformDataBinding (IEnumerable data)
1562 base.PerformDataBinding (data);
1565 protected internal virtual void PrepareControlHierarchy ()
1570 table.Caption = Caption;
1571 table.CaptionAlign = CaptionAlign;
1572 table.CopyBaseAttributes (this);
1574 foreach (GridViewRow row in table.Rows) {
1575 switch (row.RowType) {
1576 case DataControlRowType.Header:
1577 if (headerStyle != null && !headerStyle.IsEmpty)
1578 row.ControlStyle.MergeWith(headerStyle);
1579 row.Visible = ShowHeader;
1581 case DataControlRowType.Footer:
1582 if (footerStyle != null && !footerStyle.IsEmpty)
1583 row.ControlStyle.MergeWith (footerStyle);
1584 row.Visible = ShowFooter;
1586 case DataControlRowType.Pager:
1587 if (pagerStyle != null && !pagerStyle.IsEmpty)
1588 row.ControlStyle.MergeWith (pagerStyle);
1590 case DataControlRowType.EmptyDataRow:
1591 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1592 row.ControlStyle.MergeWith (emptyDataRowStyle);
1594 case DataControlRowType.DataRow:
1595 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1596 row.ControlStyle.MergeWith (editRowStyle);
1597 if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null && !selectedRowStyle.IsEmpty)
1598 row.ControlStyle.MergeWith (selectedRowStyle);
1599 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1600 row.ControlStyle.MergeWith (alternatingRowStyle);
1601 if (rowStyle != null && !rowStyle.IsEmpty)
1602 row.ControlStyle.MergeWith (rowStyle);
1608 foreach (TableCell cell in row.Cells) {
1609 DataControlFieldCell fcell = cell as DataControlFieldCell;
1610 if (fcell != null) {
1611 DataControlField field = fcell.ContainingField;
1614 if (!field.Visible) {
1615 cell.Visible = false;
1619 switch (row.RowType) {
1620 case DataControlRowType.Header:
1621 if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1622 cell.ControlStyle.MergeWith (field.HeaderStyle);
1624 case DataControlRowType.Footer:
1625 if (field.FooterStyleCreated && !field.FooterStyle.IsEmpty)
1626 cell.ControlStyle.MergeWith (field.FooterStyle);
1629 if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1630 foreach (Control c in cell.Controls) {
1631 WebControl wc = c as WebControl;
1633 wc.ControlStyle.MergeWith (field.ControlStyle);
1635 if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1636 cell.ControlStyle.MergeWith (field.ItemStyle);
1644 protected internal override void OnInit (EventArgs e)
1646 Page.RegisterRequiresControlState (this);
1650 void OnFieldsChanged (object sender, EventArgs args)
1655 protected override void OnDataPropertyChanged ()
1657 base.OnDataPropertyChanged ();
1661 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1663 base.OnDataSourceViewChanged (sender, e);
1667 protected override bool OnBubbleEvent (object source, EventArgs e)
1669 GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1671 bool causesValidation = false;
1672 IButtonControl button = args.CommandSource as IButtonControl;
1673 if (button != null && button.CausesValidation) {
1674 Page.Validate (button.ValidationGroup);
1675 causesValidation = true;
1677 OnRowCommand (args);
1678 string param = args.CommandArgument as string;
1679 if (param == null || param.Length == 0) {
1680 GridViewRow row = args.Row;
1682 param = row.RowIndex.ToString();
1684 ProcessEvent (args.CommandName, param, causesValidation);
1687 return base.OnBubbleEvent (source, e);
1690 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1692 ValidateEvent (UniqueID, eventArgument);
1693 RaisePostBackEvent (eventArgument);
1696 // This is prolly obsolete
1697 protected virtual void RaisePostBackEvent (string eventArgument)
1699 GridViewCommandEventArgs args;
1700 int i = eventArgument.IndexOf ('$');
1702 args = new GridViewCommandEventArgs (this, new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1)));
1704 args = new GridViewCommandEventArgs (this, new CommandEventArgs (eventArgument, null));
1706 OnRowCommand (args);
1707 ProcessEvent (args.CommandName, (string) args.CommandArgument, false);
1710 void ProcessEvent (string eventName, string param, bool causesValidation)
1714 case DataControlCommands.PageCommandName:
1717 case DataControlCommands.FirstPageCommandArgument:
1720 case DataControlCommands.LastPageCommandArgument:
1721 newIndex = PageCount - 1;
1723 case DataControlCommands.NextPageCommandArgument:
1724 newIndex = PageIndex + 1;
1726 case DataControlCommands.PreviousPageCommandArgument:
1727 newIndex = PageIndex - 1;
1731 int.TryParse (param, out paramIndex);
1732 newIndex = paramIndex - 1;
1735 ShowPage (newIndex);
1738 case DataControlCommands.FirstPageCommandArgument:
1742 case DataControlCommands.LastPageCommandArgument:
1743 ShowPage (PageCount - 1);
1746 case DataControlCommands.NextPageCommandArgument:
1747 if (PageIndex < PageCount - 1)
1748 ShowPage (PageIndex + 1);
1751 case DataControlCommands.PreviousPageCommandArgument:
1753 ShowPage (PageIndex - 1);
1756 case DataControlCommands.SelectCommandName:
1757 SelectRow (int.Parse (param));
1760 case DataControlCommands.EditCommandName:
1761 EditRow (int.Parse (param));
1764 case DataControlCommands.UpdateCommandName:
1765 int editIndex = int.Parse (param);
1766 UpdateRow (Rows [editIndex], editIndex, causesValidation);
1769 case DataControlCommands.CancelCommandName:
1773 case DataControlCommands.DeleteCommandName:
1774 DeleteRow (int.Parse (param));
1777 case DataControlCommands.SortCommandName:
1783 void Sort (string newSortExpression)
1785 SortDirection newDirection = SortDirection.Ascending;
1786 if (sortExpression == newSortExpression && sortDirection == SortDirection.Ascending)
1787 newDirection = SortDirection.Descending;
1789 Sort (newSortExpression, newDirection);
1792 public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
1794 GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1796 if (args.Cancel) return;
1798 if (IsBoundUsingDataSourceID) {
1801 SortExpression = args.SortExpression;
1802 SortDirection = args.SortDirection;
1805 OnSorted (EventArgs.Empty);
1808 void SelectRow (int index)
1810 GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1811 OnSelectedIndexChanging (args);
1814 SelectedIndex = args.NewSelectedIndex;
1815 OnSelectedIndexChanged (EventArgs.Empty);
1819 void ShowPage (int newIndex)
1821 GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1822 OnPageIndexChanging (args);
1824 if (args.Cancel || !IsBoundUsingDataSourceID)
1828 PageIndex = args.NewPageIndex;
1829 OnPageIndexChanged (EventArgs.Empty);
1832 void EditRow (int index)
1834 GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1835 OnRowEditing (args);
1837 if (args.Cancel || !IsBoundUsingDataSourceID)
1840 EditIndex = args.NewEditIndex;
1845 GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1846 OnRowCancelingEdit (args);
1848 if (args.Cancel || !IsBoundUsingDataSourceID)
1854 [MonoTODO ("Support two-way binding expressions")]
1855 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1857 if (rowIndex != EditIndex) throw new NotSupportedException ();
1859 GridViewRow row = Rows [rowIndex];
1860 UpdateRow (row, rowIndex, causesValidation);
1863 void UpdateRow (GridViewRow row, int rowIndex, bool causesValidation)
1865 if (causesValidation && Page != null && !Page.IsValid)
1868 currentEditOldValues = CopyOrderedDictionary (OldEditValues.Values);
1869 currentEditRowKeys = CopyOrderedDictionary (DataKeys [rowIndex].Values);
1870 currentEditNewValues = GetRowValues (row, false, false);
1872 GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (rowIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1873 OnRowUpdating (args);
1875 if (args.Cancel || !IsBoundUsingDataSourceID)
1878 DataSourceView view = GetData ();
1880 throw new HttpException ("The DataSourceView associated to data bound control was null");
1881 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1884 static IOrderedDictionary CopyOrderedDictionary (IOrderedDictionary sourceDic) {
1885 OrderedDictionary copyDic = new OrderedDictionary ();
1886 foreach (object key in sourceDic.Keys) {
1887 copyDic.Add (key, sourceDic [key]);
1892 bool UpdateCallback (int recordsAffected, Exception exception)
1894 GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1895 OnRowUpdated (dargs);
1897 if (!dargs.KeepInEditMode)
1900 return dargs.ExceptionHandled;
1903 public virtual void DeleteRow (int rowIndex)
1905 GridViewRow row = Rows [rowIndex];
1906 currentEditRowKeys = CopyOrderedDictionary (DataKeys [rowIndex].Values);
1907 currentEditNewValues = GetRowValues (row, true, true);
1909 GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1910 OnRowDeleting (args);
1912 if (args.Cancel || !IsBoundUsingDataSourceID)
1916 DataSourceView view = GetData ();
1918 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1920 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1921 OnRowDeleted (dargs);
1925 bool DeleteCallback (int recordsAffected, Exception exception)
1927 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1928 OnRowDeleted (dargs);
1929 return dargs.ExceptionHandled;
1935 oldEditValues = new DataKey (new OrderedDictionary ());
1936 currentEditRowKeys = null;
1937 currentEditOldValues = null;
1938 currentEditNewValues = null;
1941 protected internal override void LoadControlState (object ob)
1943 if (ob == null) return;
1944 object[] state = (object[]) ob;
1945 base.LoadControlState (state[0]);
1946 pageIndex = (int) state[1];
1947 selectedIndex = (int) state[2];
1948 editIndex = (int) state[3];
1949 sortExpression = (string) state[4];
1950 sortDirection = (SortDirection) state[5];
1951 DataKeyNames = (string []) state [6];
1952 if (state [7] != null)
1953 LoadDataKeyArrayState ((object []) state [7]);
1954 if (state [8] != null)
1955 ((IStateManager) OldEditValues).LoadViewState (state [8]);
1958 protected internal override object SaveControlState ()
1960 if (EnableSortingAndPagingCallbacks) {
1961 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1962 Page.ClientScript.RegisterHiddenField (ClientID + "_SortExpression", SortExpression);
1963 Page.ClientScript.RegisterHiddenField (ClientID + "_SortDirection", ((int)SortDirection).ToString());
1966 object bstate = base.SaveControlState ();
1967 return new object [] {
1975 SaveDataKeyArrayState (),
1976 (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState ())
1980 object [] SaveDataKeyArrayState ()
1985 object [] state = new object [keys.Count];
1986 for (int i = 0; i < keys.Count; i++) {
1987 state [i] = ((IStateManager) keys [i]).SaveViewState ();
1992 void LoadDataKeyArrayState (object [] state)
1994 for (int i = 0; i < state.Length; i++) {
1995 DataKey dataKey = new DataKey (new OrderedDictionary (DataKeyNames.Length), DataKeyNames);
1996 ((IStateManager) dataKey).LoadViewState (state [i]);
1997 DataKeyArrayList.Add (dataKey);
1999 keys = new DataKeyArray (DataKeyArrayList);
2002 protected override void TrackViewState()
2004 base.TrackViewState();
2005 if (columns != null) ((IStateManager)columns).TrackViewState();
2006 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
2007 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
2008 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
2009 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
2010 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
2011 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
2012 if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
2013 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
2014 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
2015 if (keys != null) ((IStateManager)keys).TrackViewState();
2016 if (autoFieldProperties != null) {
2017 foreach (IStateManager sm in autoFieldProperties)
2018 sm.TrackViewState ();
2022 protected override object SaveViewState()
2024 object[] states = new object [12];
2025 states[0] = base.SaveViewState();
2026 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
2027 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
2028 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
2029 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
2030 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
2031 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
2032 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
2033 states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
2034 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
2035 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
2037 if (autoFieldProperties != null) {
2038 object[] data = new object [autoFieldProperties.Length];
2039 bool allNull = true;
2040 for (int n=0; n<data.Length; n++) {
2041 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
2042 if (data [n] != null) allNull = false;
2044 if (!allNull) states [11] = data;
2047 for (int i = states.Length - 1; i >= 0; i--) {
2048 if (states [i] != null)
2055 protected override void LoadViewState (object savedState)
2057 if (savedState == null) {
2058 base.LoadViewState (null);
2062 object [] states = (object []) savedState;
2064 if (states[11] != null) {
2065 object[] data = (object[]) states [11];
2066 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
2067 for (int n=0; n<data.Length; n++) {
2068 IStateManager p = new AutoGeneratedFieldProperties ();
2069 p.TrackViewState ();
2070 p.LoadViewState (data [n]);
2071 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
2075 base.LoadViewState (states[0]);
2077 if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
2078 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
2079 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
2080 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
2081 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
2082 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
2083 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
2084 if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
2085 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
2086 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
2089 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
2091 RaiseCallbackEvent (eventArgs);
2094 protected virtual void RaiseCallbackEvent (string eventArgs)
2096 string[] clientData = eventArgs.Split ('|');
2097 PageIndex = int.Parse (clientData[0]);
2098 SortExpression = HttpUtility.UrlDecode (clientData [1]);
2099 SortDirection = (SortDirection) int.Parse (clientData [2]);
2101 RaisePostBackEvent (clientData[3]);
2105 string ICallbackEventHandler.GetCallbackResult ()
2107 return GetCallbackResult ();
2110 protected virtual string GetCallbackResult ()
2112 PrepareControlHierarchy ();
2114 StringWriter sw = new StringWriter ();
2115 sw.Write (PageIndex.ToString () + '|' + SortExpression + '|' + (int) SortDirection + '|');
2117 HtmlTextWriter writer = new HtmlTextWriter (sw);
2118 RenderGrid (writer);
2119 return sw.ToString ();
2122 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
2124 return GetCallbackScript (control, argument);
2127 protected virtual string GetCallbackScript (IButtonControl control, string argument)
2129 if (EnableSortingAndPagingCallbacks) {
2132 page.ClientScript.RegisterForEventValidation (UniqueID, argument);
2133 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
2138 protected override void OnPagePreLoad (object sender, EventArgs e)
2140 base.OnPagePreLoad (sender, e);
2142 if (Page.IsPostBack && EnableSortingAndPagingCallbacks) {
2144 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
2147 if (int.TryParse (Page.Request.Form [ClientID + "_SortDirection"], out dir))
2148 SortDirection = (SortDirection) dir;
2149 SortExpression = Page.Request.Form [ClientID + "_SortExpression"];
2154 const string onPreRenderScript = @"var {0} = new Object ();
2155 {0}.pageIndex = {1};
2161 protected internal override void OnPreRender (EventArgs e)
2163 base.OnPreRender (e);
2165 if (EnableSortingAndPagingCallbacks) {
2166 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
2167 string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
2168 Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
2171 string cgrid = ClientID + "_data";
2172 string script = String.Format (onPreRenderScript,
2174 ClientScriptManager.GetScriptLiteral (PageIndex),
2175 ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression),
2176 ClientScriptManager.GetScriptLiteral ((int) SortDirection),
2177 ClientScriptManager.GetScriptLiteral (UniqueID),
2180 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
2182 // Make sure the basic script infrastructure is rendered
2183 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
2184 Page.ClientScript.GetPostBackClientHyperlink (this, "");
2188 protected internal override void Render (HtmlTextWriter writer)
2190 PrepareControlHierarchy ();
2192 if (EnableSortingAndPagingCallbacks)
2193 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_div");
2194 writer.RenderBeginTag (HtmlTextWriterTag.Div);
2196 RenderGrid (writer);
2198 writer.RenderEndTag ();
2201 void RenderGrid (HtmlTextWriter writer)
2206 table.Render (writer);
2209 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
2211 if (control == null)
2212 throw new ArgumentNullException ("control");
2214 if (control.CausesValidation)
2215 throw new InvalidOperationException ("A button that causes validation in GridView '" + ID + "' is attempting to use the container GridView as the post back target. The button should either turn off validation or use itself as the post back container.");
2217 PostBackOptions options = new PostBackOptions (this);
2218 options.Argument = control.CommandName + "$" + control.CommandArgument;
2219 options.RequiresJavaScriptProtocol = true;