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;
70 TableItemStyle alternatingRowStyle;
71 TableItemStyle editRowStyle;
72 TableItemStyle emptyDataRowStyle;
73 TableItemStyle footerStyle;
74 TableItemStyle headerStyle;
75 TableItemStyle pagerStyle;
76 TableItemStyle rowStyle;
77 TableItemStyle selectedRowStyle;
79 DataKey oldEditValues;
80 AutoGeneratedFieldProperties[] autoFieldProperties;
81 string [] dataKeyNames = null;
82 readonly string[] emptyKeys = new string[0];
84 private static readonly object PageIndexChangedEvent = new object();
85 private static readonly object PageIndexChangingEvent = new object();
86 private static readonly object RowCancelingEditEvent = new object();
87 private static readonly object RowCommandEvent = new object();
88 private static readonly object RowCreatedEvent = new object();
89 private static readonly object RowDataBoundEvent = new object();
90 private static readonly object RowDeletedEvent = new object();
91 private static readonly object RowDeletingEvent = new object();
92 private static readonly object RowEditingEvent = new object();
93 private static readonly object RowUpdatedEvent = new object();
94 private static readonly object RowUpdatingEvent = new object();
95 private static readonly object SelectedIndexChangedEvent = new object();
96 private static readonly object SelectedIndexChangingEvent = new object();
97 private static readonly object SortedEvent = new object();
98 private static readonly object SortingEvent = new object();
103 int selectedIndex = -1;
105 SortDirection sortDirection = SortDirection.Ascending;
106 string sortExpression = string.Empty;
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];
199 if (eh != null) eh (this, e);
203 protected virtual void OnRowCancelingEdit (GridViewCancelEditEventArgs e)
205 if (Events != null) {
206 GridViewCancelEditEventHandler eh = (GridViewCancelEditEventHandler) Events [RowCancelingEditEvent];
207 if (eh != null) eh (this, e);
211 protected virtual void OnRowCommand (GridViewCommandEventArgs e)
213 if (Events != null) {
214 GridViewCommandEventHandler eh = (GridViewCommandEventHandler) Events [RowCommandEvent];
215 if (eh != null) eh (this, e);
219 protected virtual void OnRowCreated (GridViewRowEventArgs e)
221 if (Events != null) {
222 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowCreatedEvent];
223 if (eh != null) eh (this, e);
227 protected virtual void OnRowDataBound (GridViewRowEventArgs e)
229 if (Events != null) {
230 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowDataBoundEvent];
231 if (eh != null) eh (this, e);
235 protected virtual void OnRowDeleted (GridViewDeletedEventArgs e)
237 if (Events != null) {
238 GridViewDeletedEventHandler eh = (GridViewDeletedEventHandler) Events [RowDeletedEvent];
239 if (eh != null) eh (this, e);
243 protected virtual void OnRowDeleting (GridViewDeleteEventArgs e)
245 if (Events != null) {
246 GridViewDeleteEventHandler eh = (GridViewDeleteEventHandler) Events [RowDeletingEvent];
247 if (eh != null) eh (this, e);
251 protected virtual void OnRowEditing (GridViewEditEventArgs e)
253 if (Events != null) {
254 GridViewEditEventHandler eh = (GridViewEditEventHandler) Events [RowEditingEvent];
255 if (eh != null) eh (this, e);
259 protected virtual void OnRowUpdated (GridViewUpdatedEventArgs e)
261 if (Events != null) {
262 GridViewUpdatedEventHandler eh = (GridViewUpdatedEventHandler) Events [RowUpdatedEvent];
263 if (eh != null) eh (this, e);
267 protected virtual void OnRowUpdating (GridViewUpdateEventArgs e)
269 if (Events != null) {
270 GridViewUpdateEventHandler eh = (GridViewUpdateEventHandler) Events [RowUpdatingEvent];
271 if (eh != null) eh (this, e);
275 protected virtual void OnSelectedIndexChanged (EventArgs e)
277 if (Events != null) {
278 EventHandler eh = (EventHandler) Events [SelectedIndexChangedEvent];
279 if (eh != null) eh (this, e);
283 protected virtual void OnSelectedIndexChanging (GridViewSelectEventArgs e)
285 if (Events != null) {
286 GridViewSelectEventHandler eh = (GridViewSelectEventHandler) Events [SelectedIndexChangingEvent];
287 if (eh != null) eh (this, e);
291 protected virtual void OnSorted (EventArgs e)
293 if (Events != null) {
294 EventHandler eh = (EventHandler) Events [SortedEvent];
295 if (eh != null) eh (this, e);
299 protected virtual void OnSorting (GridViewSortEventArgs e)
301 if (Events != null) {
302 GridViewSortEventHandler eh = (GridViewSortEventHandler) Events [SortingEvent];
303 if (eh != null) eh (this, e);
308 [WebCategoryAttribute ("Paging")]
309 [DefaultValueAttribute (false)]
310 public virtual bool AllowPaging {
312 object ob = ViewState ["AllowPaging"];
313 if (ob != null) return (bool) ob;
317 ViewState ["AllowPaging"] = value;
322 [WebCategoryAttribute ("Behavior")]
323 [DefaultValueAttribute (false)]
324 public virtual bool AllowSorting {
326 object ob = ViewState ["AllowSorting"];
327 if (ob != null) return (bool) ob;
331 ViewState ["AllowSorting"] = value;
336 [WebCategoryAttribute ("Styles")]
337 [PersistenceMode (PersistenceMode.InnerProperty)]
338 [NotifyParentProperty (true)]
339 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
340 public TableItemStyle AlternatingRowStyle {
342 if (alternatingRowStyle == null) {
343 alternatingRowStyle = new TableItemStyle ();
344 if (IsTrackingViewState)
345 alternatingRowStyle.TrackViewState();
347 return alternatingRowStyle;
351 [WebCategoryAttribute ("Behavior")]
352 [DefaultValueAttribute (false)]
353 public virtual bool AutoGenerateEditButton {
355 object ob = ViewState ["AutoGenerateEditButton"];
356 if (ob != null) return (bool) ob;
360 ViewState ["AutoGenerateEditButton"] = value;
365 [WebCategoryAttribute ("Behavior")]
366 [DefaultValueAttribute (false)]
367 public virtual bool AutoGenerateDeleteButton {
369 object ob = ViewState ["AutoGenerateDeleteButton"];
370 if (ob != null) return (bool) ob;
374 ViewState ["AutoGenerateDeleteButton"] = value;
379 [WebCategoryAttribute ("Behavior")]
380 [DefaultValueAttribute (false)]
381 public virtual bool AutoGenerateSelectButton {
383 object ob = ViewState ["AutoGenerateSelectButton"];
384 if (ob != null) return (bool) ob;
388 ViewState ["AutoGenerateSelectButton"] = value;
393 [WebCategoryAttribute ("Behavior")]
394 [DefaultValueAttribute (true)]
395 public virtual bool AutoGenerateColumns {
397 object ob = ViewState ["AutoGenerateColumns"];
398 if (ob != null) return (bool) ob;
402 ViewState ["AutoGenerateColumns"] = value;
407 [UrlPropertyAttribute]
408 [WebCategoryAttribute ("Appearance")]
409 [DefaultValueAttribute ("")]
410 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
411 public virtual string BackImageUrl {
413 object ob = ViewState ["BackImageUrl"];
414 if (ob != null) return (string) ob;
418 ViewState ["BackImageUrl"] = value;
423 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
424 [BrowsableAttribute (false)]
425 public virtual GridViewRow BottomPagerRow {
428 return bottomPagerRow;
432 [WebCategoryAttribute ("Accessibility")]
433 [DefaultValueAttribute ("")]
434 [LocalizableAttribute (true)]
435 public virtual string Caption {
437 object ob = ViewState ["Caption"];
438 if (ob != null) return (string) ob;
442 ViewState ["Caption"] = value;
447 [WebCategoryAttribute ("Accessibility")]
448 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
449 public virtual TableCaptionAlign CaptionAlign
452 object o = ViewState ["CaptionAlign"];
453 if(o != null) return (TableCaptionAlign) o;
454 return TableCaptionAlign.NotSet;
457 ViewState ["CaptionAlign"] = value;
462 [WebCategoryAttribute ("Layout")]
463 [DefaultValueAttribute (-1)]
464 public virtual int CellPadding
467 object o = ViewState ["CellPadding"];
468 if (o != null) return (int) o;
472 ViewState ["CellPadding"] = value;
477 [WebCategoryAttribute ("Layout")]
478 [DefaultValueAttribute (0)]
479 public virtual int CellSpacing
482 object o = ViewState ["CellSpacing"];
483 if (o != null) return (int) o;
487 ViewState ["CellSpacing"] = value;
492 [EditorAttribute ("System.Web.UI.Design.WebControls.DataControlFieldTypeEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
493 [MergablePropertyAttribute (false)]
494 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
495 [DefaultValueAttribute (null)]
496 [WebCategoryAttribute ("Misc")]
497 public virtual DataControlFieldCollection Columns {
499 if (columns == null) {
500 columns = new DataControlFieldCollection ();
501 columns.FieldsChanged += new EventHandler (OnFieldsChanged);
502 if (IsTrackingViewState)
503 ((IStateManager)columns).TrackViewState ();
509 [DefaultValueAttribute (null)]
510 [WebCategoryAttribute ("Data")]
511 [TypeConverter (typeof(StringArrayConverter))]
512 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
513 public virtual string[] DataKeyNames
516 if (dataKeyNames != null)
521 dataKeyNames = value;
526 [BrowsableAttribute (false)]
527 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
528 public virtual DataKeyArray DataKeys {
535 [WebCategoryAttribute ("Misc")]
536 [DefaultValueAttribute (-1)]
537 public virtual int EditIndex {
547 [WebCategoryAttribute ("Styles")]
548 [PersistenceMode (PersistenceMode.InnerProperty)]
549 [NotifyParentProperty (true)]
550 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
551 public TableItemStyle EditRowStyle {
553 if (editRowStyle == null) {
554 editRowStyle = new TableItemStyle ();
555 if (IsTrackingViewState)
556 editRowStyle.TrackViewState();
562 [WebCategoryAttribute ("Styles")]
563 [PersistenceMode (PersistenceMode.InnerProperty)]
564 [NotifyParentProperty (true)]
565 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
566 public TableItemStyle EmptyDataRowStyle {
568 if (emptyDataRowStyle == null) {
569 emptyDataRowStyle = new TableItemStyle ();
570 if (IsTrackingViewState)
571 emptyDataRowStyle.TrackViewState();
573 return emptyDataRowStyle;
577 [DefaultValue (null)]
578 [TemplateContainer (typeof(GridViewRow), BindingDirection.OneWay)]
579 [PersistenceMode (PersistenceMode.InnerProperty)]
581 public virtual ITemplate EmptyDataTemplate {
582 get { return emptyDataTemplate; }
583 set { emptyDataTemplate = value; RequireBinding (); }
586 [LocalizableAttribute (true)]
587 [WebCategoryAttribute ("Appearance")]
588 [DefaultValueAttribute ("")]
589 public virtual string EmptyDataText {
591 object ob = ViewState ["EmptyDataText"];
592 if (ob != null) return (string) ob;
596 ViewState ["EmptyDataText"] = value;
601 [WebCategoryAttribute ("Behavior")]
602 [DefaultValueAttribute (false)]
603 public virtual bool EnableSortingAndPagingCallbacks {
605 object ob = ViewState ["EnableSortingAndPagingCallbacks"];
606 if (ob != null) return (bool) ob;
610 ViewState ["EnableSortingAndPagingCallbacks"] = value;
615 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
616 [BrowsableAttribute (false)]
617 public virtual GridViewRow FooterRow {
620 for (int index = table.Rows.Count - 1; index >= 0; index--) {
621 GridViewRow row = (GridViewRow) table.Rows [index];
622 switch (row.RowType) {
623 case DataControlRowType.Separator:
624 case DataControlRowType.Pager:
626 case DataControlRowType.Footer:
637 [WebCategoryAttribute ("Styles")]
638 [PersistenceMode (PersistenceMode.InnerProperty)]
639 [NotifyParentProperty (true)]
640 [DefaultValue (null)]
641 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
642 public TableItemStyle FooterStyle {
644 if (footerStyle == null) {
645 footerStyle = new TableItemStyle ();
646 if (IsTrackingViewState)
647 footerStyle.TrackViewState();
653 [WebCategoryAttribute ("Appearance")]
654 [DefaultValueAttribute (GridLines.Both)]
655 public virtual GridLines GridLines {
657 object ob = ViewState ["GridLines"];
658 if (ob != null) return (GridLines) ob;
659 return GridLines.Both;
662 ViewState ["GridLines"] = value;
666 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
667 [BrowsableAttribute (false)]
668 public virtual GridViewRow HeaderRow {
671 for (int index = 0, total = table.Rows.Count; index < total; index++) {
672 GridViewRow row = (GridViewRow) table.Rows [index];
673 switch (row.RowType) {
674 case DataControlRowType.Separator:
675 case DataControlRowType.Pager:
677 case DataControlRowType.Header:
688 [WebCategoryAttribute ("Styles")]
689 [PersistenceMode (PersistenceMode.InnerProperty)]
690 [NotifyParentProperty (true)]
691 [DefaultValue (null)]
692 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
693 public TableItemStyle HeaderStyle {
695 if (headerStyle == null) {
696 headerStyle = new TableItemStyle ();
697 if (IsTrackingViewState)
698 headerStyle.TrackViewState();
704 [Category ("Layout")]
705 [DefaultValueAttribute (HorizontalAlign.NotSet)]
706 public virtual HorizontalAlign HorizontalAlign {
708 object ob = ViewState ["HorizontalAlign"];
709 if (ob != null) return (HorizontalAlign) ob;
710 return HorizontalAlign.NotSet;
713 ViewState ["HorizontalAlign"] = value;
718 [BrowsableAttribute (false)]
719 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
720 public virtual int PageCount {
722 if (pageCount != 0) return pageCount;
728 [WebCategoryAttribute ("Paging")]
729 [BrowsableAttribute (true)]
730 [DefaultValueAttribute (0)]
731 public virtual int PageIndex {
741 [DefaultValueAttribute (10)]
742 [WebCategoryAttribute ("Paging")]
743 public virtual int PageSize {
745 object ob = ViewState ["PageSize"];
746 if (ob != null) return (int) ob;
750 ViewState ["PageSize"] = value;
755 [WebCategoryAttribute ("Paging")]
756 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
757 [NotifyParentPropertyAttribute (true)]
758 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
759 public virtual PagerSettings PagerSettings {
761 if (pagerSettings == null) {
762 pagerSettings = new PagerSettings (this);
763 if (IsTrackingViewState)
764 ((IStateManager)pagerSettings).TrackViewState ();
766 return pagerSettings;
770 [WebCategoryAttribute ("Styles")]
771 [PersistenceMode (PersistenceMode.InnerProperty)]
772 [NotifyParentProperty (true)]
773 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
774 public TableItemStyle PagerStyle {
776 if (pagerStyle == null) {
777 pagerStyle = new TableItemStyle ();
778 if (IsTrackingViewState)
779 pagerStyle.TrackViewState();
786 [DefaultValue (null)]
787 /* DataControlPagerCell isnt specified in the docs */
788 //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
789 [PersistenceMode (PersistenceMode.InnerProperty)]
791 public virtual ITemplate PagerTemplate {
792 get { return pagerTemplate; }
793 set { pagerTemplate = value; RequireBinding (); }
796 [DefaultValueAttribute ("")]
797 [WebCategoryAttribute ("Accessibility")]
798 // [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
799 public virtual string RowHeaderColumn {
801 object ob = ViewState ["RowHeaderColumn"];
802 if (ob != null) return (string) ob;
806 ViewState ["RowHeaderColumn"] = value;
811 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
812 [BrowsableAttribute (false)]
813 public virtual GridViewRowCollection Rows {
820 [WebCategoryAttribute ("Styles")]
821 [PersistenceMode (PersistenceMode.InnerProperty)]
822 [NotifyParentProperty (true)]
823 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
824 public TableItemStyle RowStyle {
826 if (rowStyle == null) {
827 rowStyle = new TableItemStyle ();
828 if (IsTrackingViewState)
829 rowStyle.TrackViewState();
835 [BrowsableAttribute (false)]
836 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
837 public virtual DataKey SelectedDataKey {
839 if (DataKeys == null)
840 throw new InvalidOperationException ("DataKeys");
842 if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
843 return DataKeys [selectedIndex];
849 [BindableAttribute (true)]
850 [DefaultValueAttribute (-1)]
851 public virtual int SelectedIndex {
853 return selectedIndex;
856 if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
857 int oldIndex = selectedIndex;
859 Rows [oldIndex].RowState = GetRowState (oldIndex);
861 selectedIndex = value;
862 if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
863 Rows [selectedIndex].RowState = GetRowState (selectedIndex);
868 [BrowsableAttribute (false)]
869 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
870 public virtual GridViewRow SelectedRow {
872 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
873 return Rows [selectedIndex];
879 [WebCategoryAttribute ("Styles")]
880 [PersistenceMode (PersistenceMode.InnerProperty)]
881 [NotifyParentProperty (true)]
882 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
883 public TableItemStyle SelectedRowStyle {
885 if (selectedRowStyle == null) {
886 selectedRowStyle = new TableItemStyle ();
887 if (IsTrackingViewState)
888 selectedRowStyle.TrackViewState();
890 return selectedRowStyle;
894 [BrowsableAttribute (false)]
895 public object SelectedValue {
897 if (SelectedDataKey != null)
898 return SelectedDataKey.Value;
904 [WebCategoryAttribute ("Appearance")]
905 [DefaultValueAttribute (false)]
906 public virtual bool ShowFooter {
908 object ob = ViewState ["ShowFooter"];
909 if (ob != null) return (bool) ob;
913 ViewState ["ShowFooter"] = value;
918 [WebCategoryAttribute ("Appearance")]
919 [DefaultValueAttribute (true)]
920 public virtual bool ShowHeader {
922 object ob = ViewState ["ShowHeader"];
923 if (ob != null) return (bool) ob;
927 ViewState ["ShowHeader"] = value;
932 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
933 [BrowsableAttribute (false)]
934 [DefaultValueAttribute (SortDirection.Ascending)]
935 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
936 public virtual SortDirection SortDirection {
937 get { return sortDirection; }
940 [BrowsableAttribute (false)]
941 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
942 public virtual string SortExpression {
943 get { return sortExpression; }
946 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
947 [BrowsableAttribute (false)]
948 public virtual GridViewRow TopPagerRow {
955 [WebCategoryAttribute ("Accessibility")]
956 [DefaultValueAttribute (true)]
957 public virtual bool UseAccessibleHeader {
959 object ob = ViewState ["UseAccessibleHeader"];
960 if (ob != null) return (bool) ob;
964 ViewState ["UseAccessibleHeader"] = value;
969 public virtual bool IsBindableType (Type type)
971 return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Guid);
974 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
976 return base.CreateDataSourceSelectArguments ();
979 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
981 ArrayList fields = new ArrayList ();
982 fields.AddRange (Columns);
984 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
985 CommandField field = new CommandField ();
986 field.ShowEditButton = AutoGenerateEditButton;
987 field.ShowDeleteButton = AutoGenerateDeleteButton;
988 field.ShowSelectButton = AutoGenerateSelectButton;
992 if (AutoGenerateColumns) {
994 autoFieldProperties = CreateAutoFieldProperties (dataSource);
996 if (autoFieldProperties != null) {
997 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
998 fields.Add (CreateAutoGeneratedColumn (props));
1005 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
1007 return new AutoGeneratedField (fieldProperties);
1010 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
1012 if(source == null) return null;
1014 PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
1017 ArrayList retVal = new ArrayList();
1021 object fitem = null;
1023 PropertyInfo prop_item = source.DataSource.GetType().GetProperty("Item",
1024 BindingFlags.Instance | BindingFlags.Static |
1025 BindingFlags.Public, null, null,
1026 new Type[] { typeof(int) }, null);
1028 if (prop_item != null) {
1029 prop_type = prop_item.PropertyType;
1032 if (prop_type == null || prop_type == typeof(object)) {
1033 IEnumerator en = source.GetEnumerator();
1037 prop_type = fitem.GetType();
1040 if (fitem != null && fitem is ICustomTypeDescriptor) {
1041 props = TypeDescriptor.GetProperties(fitem);
1042 } else if (prop_type != null) {
1043 if (IsBindableType (prop_type)) {
1044 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1045 ((IStateManager)field).TrackViewState();
1046 field.Name = "Item";
1047 field.DataField = BoundField.ThisExpression;
1048 field.Type = prop_type;
1051 props = TypeDescriptor.GetProperties (prop_type);
1056 if (props != null && props.Count > 0)
1058 foreach (PropertyDescriptor current in props) {
1059 if (IsBindableType (current.PropertyType)) {
1060 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1061 ((IStateManager)field).TrackViewState();
1062 field.Name = current.Name;
1063 field.DataField = current.Name;
1064 field.IsReadOnly = current.IsReadOnly;
1065 field.Type = current.PropertyType;
1071 if (retVal.Count > 0)
1072 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1074 return new AutoGeneratedFieldProperties [0];
1077 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1079 GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1080 OnRowCreated (new GridViewRowEventArgs (row));
1084 void RequireBinding ()
1087 RequiresDataBinding = true;
1092 protected virtual Table CreateChildTable ()
1094 Table table = new Table ();
1095 table.Caption = Caption;
1096 table.CaptionAlign = CaptionAlign;
1097 table.CellPadding = CellPadding;
1098 table.CellSpacing = CellSpacing;
1099 table.HorizontalAlign = HorizontalAlign;
1100 table.BackImageUrl = BackImageUrl;
1104 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1106 PagedDataSource dataSource;
1109 DataSourceView view = GetData ();
1110 dataSource = new PagedDataSource ();
1111 dataSource.DataSource = data;
1114 dataSource.AllowPaging = true;
1115 dataSource.PageSize = PageSize;
1116 dataSource.CurrentPageIndex = PageIndex;
1118 dataSource.AllowServerPaging = true;
1119 if (view.CanRetrieveTotalRowCount)
1120 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1122 dataSource.DataSourceView = view;
1123 dataSource.DataSourceSelectArguments = SelectArguments;
1124 dataSource.SetItemCountFromPageIndex (PageIndex + PagerSettings.PageButtonCount);
1129 pageCount = dataSource.PageCount;
1133 dataSource = new PagedDataSource ();
1134 dataSource.DataSource = data;
1136 dataSource.AllowPaging = true;
1137 dataSource.PageSize = PageSize;
1138 dataSource.CurrentPageIndex = PageIndex;
1142 bool showPager = AllowPaging && (PageCount > 1);
1145 table = CreateChildTable ();
1146 Controls.Add (table);
1148 ArrayList list = new ArrayList ();
1149 ArrayList keyList = new ArrayList ();
1151 // Creates the set of fields to show
1153 ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1154 DataControlField[] fields = new DataControlField [fieldCollection.Count];
1155 fieldCollection.CopyTo (fields, 0);
1157 foreach (DataControlField field in fields) {
1158 field.Initialize (AllowSorting, this);
1159 if (EnableSortingAndPagingCallbacks)
1160 field.ValidateSupportsCallback ();
1163 // Main table creation
1165 if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
1166 topPagerRow = CreatePagerRow (fields.Length, dataSource);
1167 table.Rows.Add (topPagerRow);
1170 GridViewRow headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
1171 table.Rows.Add (headerRow);
1172 InitializeRow (headerRow, fields);
1174 foreach (object obj in dataSource) {
1175 DataControlRowState rstate = GetRowState (list.Count);
1176 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1179 table.Rows.Add (row);
1180 InitializeRow (row, fields);
1183 OnRowDataBound (new GridViewRowEventArgs (row));
1184 if (EditIndex == row.RowIndex)
1185 oldEditValues = new DataKey (GetRowValues (row, false, true));
1186 keyList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1188 if (EditIndex == row.RowIndex)
1189 oldEditValues = new DataKey (new OrderedDictionary ());
1190 keyList.Add (new DataKey (new OrderedDictionary (), DataKeyNames));
1193 if (list.Count >= PageSize)
1197 if (list.Count == 0)
1198 table.Rows.Add (CreateEmptyrRow (fields.Length));
1200 GridViewRow footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
1201 table.Rows.Add (footerRow);
1202 InitializeRow (footerRow, fields);
1204 if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
1205 bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
1206 table.Rows.Add (bottomPagerRow);
1209 rows = new GridViewRowCollection (list);
1210 keys = new DataKeyArray (keyList);
1212 return dataSource.DataSourceCount;
1216 protected override Style CreateControlStyle ()
1218 style = new TableStyle (ViewState);
1219 style.GridLines = GridLines.Both;
1220 style.CellSpacing = 0;
1224 DataControlRowState GetRowState (int index)
1226 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1227 if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1228 if (index == EditIndex) rstate |= DataControlRowState.Edit;
1232 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1234 GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1235 InitializePager (row, fieldCount, dataSource);
1239 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1241 TableCell cell = new TableCell ();
1243 cell.ColumnSpan = columnSpan;
1245 if (pagerTemplate != null)
1246 pagerTemplate.InstantiateIn (cell);
1248 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1250 row.Cells.Add (cell);
1253 GridViewRow CreateEmptyrRow (int fieldCount)
1255 GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1256 TableCell cell = new TableCell ();
1257 cell.ColumnSpan = fieldCount;
1259 if (emptyDataTemplate != null)
1260 emptyDataTemplate.InstantiateIn (cell);
1262 cell.Text = EmptyDataText;
1264 row.Cells.Add (cell);
1268 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1270 DataControlCellType ctype;
1271 bool accessibleHeader = false;
1273 switch (row.RowType) {
1274 case DataControlRowType.Header:
1275 ctype = DataControlCellType.Header;
1276 accessibleHeader = UseAccessibleHeader;
1278 case DataControlRowType.Footer:
1279 ctype = DataControlCellType.Footer;
1282 ctype = DataControlCellType.DataCell;
1286 for (int n=0; n<fields.Length; n++) {
1287 DataControlField field = fields [n];
1288 DataControlFieldCell cell;
1289 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1290 cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1292 cell = new DataControlFieldCell (field);
1293 row.Cells.Add (cell);
1294 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1298 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1300 if (cachedKeyProperties == null) {
1301 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1302 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1303 for (int n=0; n<DataKeyNames.Length; n++) {
1304 PropertyDescriptor p = props [DataKeyNames[n]];
1306 new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + row.DataItem.GetType());
1307 cachedKeyProperties [n] = p;
1311 OrderedDictionary dic = new OrderedDictionary ();
1312 foreach (PropertyDescriptor p in cachedKeyProperties)
1313 dic [p.Name] = p.GetValue (row.DataItem);
1317 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1319 OrderedDictionary dic = new OrderedDictionary ();
1320 ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1324 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1326 foreach (TableCell cell in row.Cells) {
1327 DataControlFieldCell c = cell as DataControlFieldCell;
1329 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1331 if (!includePrimaryKey && DataKeyNames != null)
1332 foreach (string key in DataKeyNames)
1333 fieldValues.Remove (key);
1336 protected override HtmlTextWriterTag TagKey {
1338 if (EnableSortingAndPagingCallbacks)
1339 return HtmlTextWriterTag.Div;
1341 return HtmlTextWriterTag.Table;
1345 public sealed override void DataBind ()
1347 DataSourceView view = GetData ();
1348 if (AllowPaging && view.CanPage) {
1349 SelectArguments.StartRowIndex = PageIndex * PageSize;
1350 SelectArguments.MaximumRows = PageSize;
1351 if (view.CanRetrieveTotalRowCount)
1352 SelectArguments.RetrieveTotalRowCount = true;
1355 if (sortExpression != "") {
1356 if (sortDirection == SortDirection.Ascending)
1357 SelectArguments.SortExpression = sortExpression;
1359 SelectArguments.SortExpression = sortExpression + " DESC";
1362 cachedKeyProperties = null;
1366 protected internal override void PerformDataBinding (IEnumerable data)
1368 base.PerformDataBinding (data);
1372 protected internal virtual void PrepareControlHierarchy ()
1374 throw new NotImplementedException ();
1377 protected internal override void OnInit (EventArgs e)
1379 Page.RegisterRequiresControlState (this);
1383 void OnFieldsChanged (object sender, EventArgs args)
1388 protected override void OnDataPropertyChanged ()
1390 base.OnDataPropertyChanged ();
1394 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1396 base.OnDataSourceViewChanged (sender, e);
1400 protected override bool OnBubbleEvent (object source, EventArgs e)
1402 GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1404 OnRowCommand (args);
1405 string param = args.CommandArgument as string;
1406 if (param == null || param.Length == 0) {
1407 GridViewRow row = args.Row;
1409 param = row.RowIndex.ToString();
1411 ProcessEvent (args.CommandName, param);
1413 return base.OnBubbleEvent (source, e);
1416 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1418 RaisePostBackEvent (eventArgument);
1421 // This is prolly obsolete
1422 protected virtual void RaisePostBackEvent (string eventArgument)
1424 int i = eventArgument.IndexOf ('$');
1426 ProcessEvent (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1428 ProcessEvent (eventArgument, null);
1431 void ProcessEvent (string eventName, string param)
1435 case DataControlCommands.PageCommandName:
1438 case DataControlCommands.FirstPageCommandArgument:
1441 case DataControlCommands.LastPageCommandArgument:
1442 newIndex = PageCount - 1;
1444 case DataControlCommands.NextPageCommandArgument:
1445 if (PageIndex < PageCount - 1) newIndex = PageIndex + 1;
1447 case DataControlCommands.PreviousPageCommandArgument:
1448 if (PageIndex > 0) newIndex = PageIndex - 1;
1451 newIndex = int.Parse (param) - 1;
1454 ShowPage (newIndex);
1457 case DataControlCommands.FirstPageCommandArgument:
1461 case DataControlCommands.LastPageCommandArgument:
1462 ShowPage (PageCount - 1);
1465 case DataControlCommands.NextPageCommandArgument:
1466 if (PageIndex < PageCount - 1)
1467 ShowPage (PageIndex + 1);
1470 case DataControlCommands.PreviousPageCommandArgument:
1472 ShowPage (PageIndex - 1);
1475 case DataControlCommands.SelectCommandName:
1476 SelectRow (int.Parse (param));
1479 case DataControlCommands.EditCommandName:
1480 EditRow (int.Parse (param));
1483 case DataControlCommands.UpdateCommandName:
1484 UpdateRow (EditIndex, true);
1487 case DataControlCommands.CancelCommandName:
1491 case DataControlCommands.DeleteCommandName:
1492 DeleteRow (int.Parse (param));
1495 case DataControlCommands.SortCommandName:
1501 void Sort (string newSortExpression)
1503 SortDirection newDirection;
1504 if (sortExpression == newSortExpression) {
1505 if (sortDirection == SortDirection.Ascending)
1506 newDirection = SortDirection.Descending;
1508 newDirection = SortDirection.Ascending;
1510 newDirection = sortDirection;
1512 Sort (newSortExpression, newDirection);
1515 public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
1517 GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1519 if (args.Cancel) return;
1521 sortExpression = args.SortExpression;
1522 sortDirection = args.SortDirection;
1525 OnSorted (EventArgs.Empty);
1528 void SelectRow (int index)
1530 GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1531 OnSelectedIndexChanging (args);
1533 SelectedIndex = args.NewSelectedIndex;
1534 OnSelectedIndexChanged (EventArgs.Empty);
1538 void ShowPage (int newIndex)
1540 GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1541 OnPageIndexChanging (args);
1544 PageIndex = args.NewPageIndex;
1545 OnPageIndexChanged (EventArgs.Empty);
1549 void EditRow (int index)
1551 GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1552 OnRowEditing (args);
1554 EditIndex = args.NewEditIndex;
1560 GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1561 OnRowCancelingEdit (args);
1567 [MonoTODO ("Support two-way binding expressions")]
1568 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1570 if (causesValidation)
1573 if (rowIndex != EditIndex) throw new NotSupportedException ();
1575 currentEditOldValues = oldEditValues.Values;
1577 GridViewRow row = Rows [rowIndex];
1578 currentEditRowKeys = DataKeys [rowIndex].Values;
1579 currentEditNewValues = GetRowValues (row, false, false);
1581 GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (EditIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1582 OnRowUpdating (args);
1584 DataSourceView view = GetData ();
1585 if (view == null) throw new HttpException ("The DataSourceView associated to data bound control was null");
1586 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1591 bool UpdateCallback (int recordsAffected, Exception exception)
1593 GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1594 OnRowUpdated (dargs);
1596 if (!dargs.KeepInEditMode)
1599 return dargs.ExceptionHandled;
1602 public virtual void DeleteRow (int rowIndex)
1604 GridViewRow row = Rows [rowIndex];
1605 currentEditRowKeys = DataKeys [rowIndex].Values;
1606 currentEditNewValues = GetRowValues (row, true, true);
1608 GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1609 OnRowDeleting (args);
1613 DataSourceView view = GetData ();
1615 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1617 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1618 OnRowDeleted (dargs);
1623 bool DeleteCallback (int recordsAffected, Exception exception)
1625 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1626 OnRowDeleted (dargs);
1627 return dargs.ExceptionHandled;
1633 oldEditValues = new DataKey (new OrderedDictionary ());
1634 currentEditRowKeys = null;
1635 currentEditOldValues = null;
1636 currentEditNewValues = null;
1639 protected internal override void LoadControlState (object ob)
1641 if (ob == null) return;
1642 object[] state = (object[]) ob;
1643 base.LoadControlState (state[0]);
1644 pageIndex = (int) state[1];
1645 pageCount = (int) state[2];
1646 selectedIndex = (int) state[3];
1647 editIndex = (int) state[4];
1648 sortExpression = (string) state[5];
1649 sortDirection = (SortDirection) state[6];
1650 DataKeyNames = (string []) state [7];
1653 protected internal override object SaveControlState ()
1655 object bstate = base.SaveControlState ();
1656 return new object[] {
1657 bstate, pageIndex, pageCount, selectedIndex, editIndex, sortExpression, sortDirection, DataKeyNames
1661 protected override void TrackViewState()
1663 base.TrackViewState();
1664 if (columns != null) ((IStateManager)columns).TrackViewState();
1665 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1666 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1667 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1668 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1669 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1670 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1671 if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
1672 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1673 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1674 if (keys != null) ((IStateManager)keys).TrackViewState();
1675 if (autoFieldProperties != null) {
1676 foreach (IStateManager sm in autoFieldProperties)
1677 sm.TrackViewState ();
1681 protected override object SaveViewState()
1683 object[] states = new object [14];
1684 states[0] = base.SaveViewState();
1685 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
1686 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1687 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
1688 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1689 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1690 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1691 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1692 states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
1693 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1694 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1695 states[11] = (keys == null ? null : ((IStateManager)keys).SaveViewState());
1696 states[12] = (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState());
1698 if (autoFieldProperties != null) {
1699 object[] data = new object [autoFieldProperties.Length];
1700 bool allNull = true;
1701 for (int n=0; n<data.Length; n++) {
1702 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
1703 if (data [n] != null) allNull = false;
1705 if (!allNull) states [13] = data;
1708 for (int i = states.Length - 1; i >= 0; i--) {
1709 if (states [i] != null)
1716 protected override void LoadViewState (object savedState)
1718 if (savedState == null) {
1719 base.LoadViewState (null);
1723 object [] states = (object []) savedState;
1725 if (states[13] != null) {
1726 object[] data = (object[]) states [13];
1727 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
1728 for (int n=0; n<data.Length; n++) {
1729 IStateManager p = new AutoGeneratedFieldProperties ();
1730 p.TrackViewState ();
1731 p.LoadViewState (data [n]);
1732 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
1736 base.LoadViewState (states[0]);
1737 EnsureChildControls ();
1739 if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
1740 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1741 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
1742 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1743 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1744 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1745 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1746 if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
1747 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1748 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1749 if (states[11] != null) ((IStateManager)DataKeys).LoadViewState (states[11]);
1750 if (states[12] != null && oldEditValues != null) ((IStateManager)oldEditValues).LoadViewState (states[12]);
1753 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
1755 RaiseCallbackEvent (eventArgs);
1758 string callbackResult;
1759 protected virtual void RaiseCallbackEvent (string eventArgs)
1761 string[] clientData = eventArgs.Split ('|');
1762 pageIndex = int.Parse (clientData[0]);
1763 sortExpression = HttpUtility.UrlDecode (clientData[1]);
1764 if (sortExpression == "") sortExpression = null;
1767 RaisePostBackEvent (clientData[2]);
1770 StringWriter sw = new StringWriter ();
1771 sw.Write (PageIndex.ToString() + '|' + SortExpression + '|');
1773 HtmlTextWriter writer = new HtmlTextWriter (sw);
1774 RenderGrid (writer);
1775 callbackResult = sw.ToString ();
1778 string ICallbackEventHandler.GetCallbackResult ()
1780 return GetCallbackResult ();
1783 protected virtual string GetCallbackResult ()
1785 return callbackResult;
1788 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
1790 return GetCallbackScript (control, argument);
1793 protected virtual string GetCallbackScript (IButtonControl control, string argument)
1795 if (EnableSortingAndPagingCallbacks)
1796 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
1802 protected override void OnPagePreLoad (object sender, EventArgs e)
1804 base.OnPagePreLoad (sender, e);
1807 protected internal override void OnPreRender (EventArgs e)
1809 base.OnPreRender (e);
1811 if (EnableSortingAndPagingCallbacks)
1813 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
1814 string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
1815 Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
1818 string cgrid = ClientID + "_data";
1819 string script = string.Format ("var {0} = new Object ();\n", cgrid);
1820 script += string.Format ("{0}.pageIndex = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (PageIndex));
1821 script += string.Format ("{0}.sortExp = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression));
1822 script += string.Format ("{0}.uid = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (UniqueID));
1823 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
1825 // Make sure the basic script infrastructure is rendered
1826 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
1827 Page.ClientScript.GetPostBackClientHyperlink (this, "");
1831 protected internal override void Render (HtmlTextWriter writer)
1833 if (EnableSortingAndPagingCallbacks)
1834 base.RenderBeginTag (writer);
1836 writer.RenderBeginTag (HtmlTextWriterTag.Div);
1838 RenderGrid (writer);
1840 if (EnableSortingAndPagingCallbacks)
1841 base.RenderEndTag (writer);
1843 writer.RenderEndTag ();
1846 void RenderGrid (HtmlTextWriter writer)
1851 table.GridLines = GridLines;
1852 table.RenderBeginTag (writer);
1854 foreach (GridViewRow row in table.Rows)
1856 switch (row.RowType) {
1857 case DataControlRowType.Header:
1858 if (!ShowHeader) continue;
1859 if (headerStyle != null)headerStyle.AddAttributesToRender (writer, row);
1861 case DataControlRowType.Footer:
1862 if (!ShowFooter) continue;
1863 if (footerStyle != null) footerStyle.AddAttributesToRender (writer, row);
1865 case DataControlRowType.Pager:
1866 if (pagerStyle != null) pagerStyle.AddAttributesToRender (writer, row);
1868 case DataControlRowType.EmptyDataRow:
1869 if (emptyDataRowStyle != null) emptyDataRowStyle.AddAttributesToRender (writer, row);
1875 if ((row.RowState & DataControlRowState.Normal) != 0 && rowStyle != null)
1876 rowStyle.AddAttributesToRender (writer, row);
1877 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null)
1878 alternatingRowStyle.AddAttributesToRender (writer, row);
1879 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null)
1880 editRowStyle.AddAttributesToRender (writer, row);
1881 if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null)
1882 selectedRowStyle.AddAttributesToRender (writer, row);
1884 row.RenderBeginTag (writer);
1886 foreach (TableCell cell in row.Cells) {
1887 DataControlFieldCell fcell = cell as DataControlFieldCell;
1888 if (fcell != null) {
1889 Style cellStyle = null;
1890 switch (row.RowType) {
1891 case DataControlRowType.Header: cellStyle = fcell.ContainingField.HeaderStyle; break;
1892 case DataControlRowType.Footer: cellStyle = fcell.ContainingField.FooterStyle; break;
1893 default: cellStyle = fcell.ContainingField.ItemStyle; break;
1895 if (cellStyle != null)
1896 cellStyle.AddAttributesToRender (writer, cell);
1898 cell.Render (writer);
1900 row.RenderEndTag (writer);
1902 table.RenderEndTag (writer);
1906 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1908 PostBackOptions pbo = new PostBackOptions (this, control.CommandName + "$" + control.CommandArgument);