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 [DesignerAttribute ("System.Web.UI.Design.WebControls.GridViewDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner")]
44 [ControlValuePropertyAttribute ("SelectedValue")]
45 [DefaultEventAttribute ("SelectedIndexChanged")]
46 [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
47 [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48 public class GridView: CompositeDataBoundControl, ICallbackEventHandler, ICallbackContainer
51 GridViewRowCollection rows;
52 GridViewRow headerRow;
53 GridViewRow footerRow;
54 GridViewRow bottomPagerRow;
55 GridViewRow topPagerRow;
57 IOrderedDictionary currentEditRowKeys;
58 IOrderedDictionary currentEditNewValues;
59 IOrderedDictionary currentEditOldValues;
61 ITemplate pagerTemplate;
62 ITemplate emptyDataTemplate;
64 PropertyDescriptor[] cachedKeyProperties;
67 DataControlFieldCollection columns;
68 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 readonly string[] emptyKeys = new string[0];
83 private static readonly object PageIndexChangedEvent = new object();
84 private static readonly object PageIndexChangingEvent = new object();
85 private static readonly object RowCancelingEditEvent = new object();
86 private static readonly object RowCommandEvent = new object();
87 private static readonly object RowCreatedEvent = new object();
88 private static readonly object RowDataBoundEvent = new object();
89 private static readonly object RowDeletedEvent = new object();
90 private static readonly object RowDeletingEvent = new object();
91 private static readonly object RowEditingEvent = new object();
92 private static readonly object RowUpdatedEvent = new object();
93 private static readonly object RowUpdatingEvent = new object();
94 private static readonly object SelectedIndexChangedEvent = new object();
95 private static readonly object SelectedIndexChangingEvent = new object();
96 private static readonly object SortedEvent = new object();
97 private static readonly object SortingEvent = new object();
102 int selectedIndex = -1;
104 SortDirection sortDirection = SortDirection.Ascending;
105 string sortExpression;
111 public event EventHandler PageIndexChanged {
112 add { Events.AddHandler (PageIndexChangedEvent, value); }
113 remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
116 public event GridViewPageEventHandler PageIndexChanging {
117 add { Events.AddHandler (PageIndexChangingEvent, value); }
118 remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
121 public event GridViewCancelEditEventHandler RowCancelingEdit {
122 add { Events.AddHandler (RowCancelingEditEvent, value); }
123 remove { Events.RemoveHandler (RowCancelingEditEvent, value); }
126 public event GridViewCommandEventHandler RowCommand {
127 add { Events.AddHandler (RowCommandEvent, value); }
128 remove { Events.RemoveHandler (RowCommandEvent, value); }
131 public event GridViewRowEventHandler RowCreated {
132 add { Events.AddHandler (RowCreatedEvent, value); }
133 remove { Events.RemoveHandler (RowCreatedEvent, value); }
136 public event GridViewRowEventHandler RowDataBound {
137 add { Events.AddHandler (RowDataBoundEvent, value); }
138 remove { Events.RemoveHandler (RowDataBoundEvent, value); }
141 public event GridViewDeletedEventHandler RowDeleted {
142 add { Events.AddHandler (RowDeletedEvent, value); }
143 remove { Events.RemoveHandler (RowDeletedEvent, value); }
146 public event GridViewDeleteEventHandler RowDeleting {
147 add { Events.AddHandler (RowDeletingEvent, value); }
148 remove { Events.RemoveHandler (RowDeletingEvent, value); }
151 public event GridViewEditEventHandler RowEditing {
152 add { Events.AddHandler (RowEditingEvent, value); }
153 remove { Events.RemoveHandler (RowEditingEvent, value); }
156 public event GridViewUpdatedEventHandler RowUpdated {
157 add { Events.AddHandler (RowUpdatedEvent, value); }
158 remove { Events.RemoveHandler (RowUpdatedEvent, value); }
161 public event GridViewUpdateEventHandler RowUpdating {
162 add { Events.AddHandler (RowUpdatingEvent, value); }
163 remove { Events.RemoveHandler (RowUpdatingEvent, value); }
166 public event EventHandler SelectedIndexChanged {
167 add { Events.AddHandler (SelectedIndexChangedEvent, value); }
168 remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
171 public event GridViewSelectEventHandler SelectedIndexChanging {
172 add { Events.AddHandler (SelectedIndexChangingEvent, value); }
173 remove { Events.RemoveHandler (SelectedIndexChangingEvent, value); }
176 public event EventHandler Sorted {
177 add { Events.AddHandler (SortedEvent, value); }
178 remove { Events.RemoveHandler (SortedEvent, value); }
181 public event GridViewSortEventHandler Sorting {
182 add { Events.AddHandler (SortingEvent, value); }
183 remove { Events.RemoveHandler (SortingEvent, value); }
186 protected virtual void OnPageIndexChanged (EventArgs e)
188 if (Events != null) {
189 EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
190 if (eh != null) eh (this, e);
194 protected virtual void OnPageIndexChanging (GridViewPageEventArgs e)
196 if (Events != null) {
197 GridViewPageEventHandler eh = (GridViewPageEventHandler) Events [PageIndexChangingEvent];
198 if (eh != null) eh (this, e);
202 protected virtual void OnRowCancelingEdit (GridViewCancelEditEventArgs e)
204 if (Events != null) {
205 GridViewCancelEditEventHandler eh = (GridViewCancelEditEventHandler) Events [RowCancelingEditEvent];
206 if (eh != null) eh (this, e);
210 protected virtual void OnRowCommand (GridViewCommandEventArgs e)
212 if (Events != null) {
213 GridViewCommandEventHandler eh = (GridViewCommandEventHandler) Events [RowCommandEvent];
214 if (eh != null) eh (this, e);
218 protected virtual void OnRowCreated (GridViewRowEventArgs e)
220 if (Events != null) {
221 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowCreatedEvent];
222 if (eh != null) eh (this, e);
226 protected virtual void OnRowDataBound (GridViewRowEventArgs e)
228 if (Events != null) {
229 GridViewRowEventHandler eh = (GridViewRowEventHandler) Events [RowDataBoundEvent];
230 if (eh != null) eh (this, e);
234 protected virtual void OnRowDeleted (GridViewDeletedEventArgs e)
236 if (Events != null) {
237 GridViewDeletedEventHandler eh = (GridViewDeletedEventHandler) Events [RowDeletedEvent];
238 if (eh != null) eh (this, e);
242 protected virtual void OnRowDeleting (GridViewDeleteEventArgs e)
244 if (Events != null) {
245 GridViewDeleteEventHandler eh = (GridViewDeleteEventHandler) Events [RowDeletingEvent];
246 if (eh != null) eh (this, e);
250 protected virtual void OnRowEditing (GridViewEditEventArgs e)
252 if (Events != null) {
253 GridViewEditEventHandler eh = (GridViewEditEventHandler) Events [RowEditingEvent];
254 if (eh != null) eh (this, e);
258 protected virtual void OnRowUpdated (GridViewUpdatedEventArgs e)
260 if (Events != null) {
261 GridViewUpdatedEventHandler eh = (GridViewUpdatedEventHandler) Events [RowUpdatedEvent];
262 if (eh != null) eh (this, e);
266 protected virtual void OnRowUpdating (GridViewUpdateEventArgs e)
268 if (Events != null) {
269 GridViewUpdateEventHandler eh = (GridViewUpdateEventHandler) Events [RowUpdatingEvent];
270 if (eh != null) eh (this, e);
274 protected virtual void OnSelectedIndexChanged (EventArgs e)
276 if (Events != null) {
277 EventHandler eh = (EventHandler) Events [SelectedIndexChangedEvent];
278 if (eh != null) eh (this, e);
282 protected virtual void OnSelectedIndexChanging (GridViewSelectEventArgs e)
284 if (Events != null) {
285 GridViewSelectEventHandler eh = (GridViewSelectEventHandler) Events [SelectedIndexChangingEvent];
286 if (eh != null) eh (this, e);
290 protected virtual void OnSorted (EventArgs e)
292 if (Events != null) {
293 EventHandler eh = (EventHandler) Events [SortedEvent];
294 if (eh != null) eh (this, e);
298 protected virtual void OnSorting (GridViewSortEventArgs e)
300 if (Events != null) {
301 GridViewSortEventHandler eh = (GridViewSortEventHandler) Events [SortingEvent];
302 if (eh != null) eh (this, e);
307 [WebCategoryAttribute ("Paging")]
308 [DefaultValueAttribute (false)]
309 public bool AllowPaging {
311 object ob = ViewState ["AllowPaging"];
312 if (ob != null) return (bool) ob;
316 ViewState ["AllowPaging"] = value;
321 [WebCategoryAttribute ("Behavior")]
322 [DefaultValueAttribute (false)]
323 public bool AllowSorting {
325 object ob = ViewState ["AllowSorting"];
326 if (ob != null) return (bool) ob;
330 ViewState ["AllowSorting"] = value;
335 [WebCategoryAttribute ("Styles")]
336 [PersistenceMode (PersistenceMode.InnerProperty)]
337 [NotifyParentProperty (true)]
338 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
339 public virtual TableItemStyle AlternatingRowStyle {
341 if (alternatingRowStyle == null) {
342 alternatingRowStyle = new TableItemStyle ();
343 if (IsTrackingViewState)
344 alternatingRowStyle.TrackViewState();
346 return alternatingRowStyle;
350 [WebCategoryAttribute ("Behavior")]
351 [DefaultValueAttribute (false)]
352 public virtual bool AutoGenerateEditButton {
354 object ob = ViewState ["AutoGenerateEditButton"];
355 if (ob != null) return (bool) ob;
359 ViewState ["AutoGenerateEditButton"] = value;
364 [WebCategoryAttribute ("Behavior")]
365 [DefaultValueAttribute (false)]
366 public virtual bool AutoGenerateDeleteButton {
368 object ob = ViewState ["AutoGenerateDeleteButton"];
369 if (ob != null) return (bool) ob;
373 ViewState ["AutoGenerateDeleteButton"] = value;
378 [WebCategoryAttribute ("Behavior")]
379 [DefaultValueAttribute (false)]
380 public virtual bool AutoGenerateSelectButton {
382 object ob = ViewState ["AutoGenerateSelectButton"];
383 if (ob != null) return (bool) ob;
387 ViewState ["AutoGenerateSelectButton"] = value;
392 [WebCategoryAttribute ("Behavior")]
393 [DefaultValueAttribute (true)]
394 public virtual bool AutoGenerateColumns {
396 object ob = ViewState ["AutoGenerateColumns"];
397 if (ob != null) return (bool) ob;
401 ViewState ["AutoGenerateColumns"] = value;
406 [UrlPropertyAttribute]
407 [WebCategoryAttribute ("Appearance")]
408 [DefaultValueAttribute ("")]
409 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
410 public virtual string BackImageUrl {
412 object ob = ViewState ["BackImageUrl"];
413 if (ob != null) return (string) ob;
417 ViewState ["BackImageUrl"] = value;
422 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
423 [BrowsableAttribute (false)]
424 public virtual GridViewRow BottomPagerRow {
427 return bottomPagerRow;
431 [WebCategoryAttribute ("Accessibility")]
432 [DefaultValueAttribute ("")]
433 [LocalizableAttribute (true)]
434 public string Caption {
436 object ob = ViewState ["Caption"];
437 if (ob != null) return (string) ob;
441 ViewState ["Caption"] = value;
446 [WebCategoryAttribute ("Accessibility")]
447 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
448 public virtual TableCaptionAlign CaptionAlign
451 object o = ViewState ["CaptionAlign"];
452 if(o != null) return (TableCaptionAlign) o;
453 return TableCaptionAlign.NotSet;
456 ViewState ["CaptionAlign"] = value;
461 [WebCategoryAttribute ("Layout")]
462 [DefaultValueAttribute (-1)]
463 public virtual int CellPadding
466 object o = ViewState ["CellPadding"];
467 if (o != null) return (int) o;
471 ViewState ["CellPadding"] = value;
476 [WebCategoryAttribute ("Layout")]
477 [DefaultValueAttribute (0)]
478 public virtual int CellSpacing
481 object o = ViewState ["CellSpacing"];
482 if (o != null) return (int) o;
486 ViewState ["CellSpacing"] = value;
491 [EditorAttribute ("System.Web.UI.Design.WebControls.DataControlFieldTypeEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
492 [MergablePropertyAttribute (false)]
493 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
494 [DefaultValueAttribute (null)]
495 [WebCategoryAttribute ("Misc")]
496 public virtual DataControlFieldCollection Columns {
498 if (columns == null) {
499 columns = new DataControlFieldCollection ();
500 columns.FieldsChanged += new EventHandler (OnFieldsChanged);
501 if (IsTrackingViewState)
502 ((IStateManager)columns).TrackViewState ();
508 [DefaultValueAttribute (null)]
509 [WebCategoryAttribute ("Data")]
510 [TypeConverter (typeof(StringArrayConverter))]
511 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
512 public virtual string[] DataKeyNames
515 object o = ViewState ["DataKeyNames"];
516 if (o != null) return (string[]) o;
520 ViewState ["DataKeyNames"] = value;
525 [BrowsableAttribute (false)]
526 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
527 public virtual DataKeyArray DataKeys {
534 [WebCategoryAttribute ("Misc")]
535 [DefaultValueAttribute (-1)]
536 public int EditIndex {
546 [WebCategoryAttribute ("Styles")]
547 [PersistenceMode (PersistenceMode.InnerProperty)]
548 [NotifyParentProperty (true)]
549 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
550 public virtual TableItemStyle EditRowStyle {
552 if (editRowStyle == null) {
553 editRowStyle = new TableItemStyle ();
554 if (IsTrackingViewState)
555 editRowStyle.TrackViewState();
561 [WebCategoryAttribute ("Styles")]
562 [PersistenceMode (PersistenceMode.InnerProperty)]
563 [NotifyParentProperty (true)]
564 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
565 public virtual TableItemStyle EmptyDataRowStyle {
567 if (emptyDataRowStyle == null) {
568 emptyDataRowStyle = new TableItemStyle ();
569 if (IsTrackingViewState)
570 emptyDataRowStyle.TrackViewState();
572 return emptyDataRowStyle;
576 [DefaultValue (null)]
577 [TemplateContainer (typeof(GridView), BindingDirection.OneWay)]
578 [PersistenceMode (PersistenceMode.InnerProperty)]
580 public ITemplate EmptyDataTemplate {
581 get { return emptyDataTemplate; }
582 set { emptyDataTemplate = value; RequireBinding (); }
585 [LocalizableAttribute (true)]
586 [WebCategoryAttribute ("Appearance")]
587 [DefaultValueAttribute ("")]
588 public virtual string EmptyDataText {
590 object ob = ViewState ["EmptyDataText"];
591 if (ob != null) return (string) ob;
595 ViewState ["EmptyDataText"] = value;
600 [WebCategoryAttribute ("Behavior")]
601 [DefaultValueAttribute (false)]
602 public virtual bool EnableSortingAndPagingCallbacks {
604 object ob = ViewState ["EnableSortingAndPagingCallbacks"];
605 if (ob != null) return (bool) ob;
609 ViewState ["EnableSortingAndPagingCallbacks"] = value;
614 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
615 [BrowsableAttribute (false)]
616 public virtual GridViewRow FooterRow {
618 if (footerRow == null)
619 footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
624 [WebCategoryAttribute ("Styles")]
625 [PersistenceMode (PersistenceMode.InnerProperty)]
626 [NotifyParentProperty (true)]
627 [DefaultValue (null)]
628 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
629 public virtual TableItemStyle FooterStyle {
631 if (footerStyle == null) {
632 footerStyle = new TableItemStyle ();
633 if (IsTrackingViewState)
634 footerStyle.TrackViewState();
640 [WebCategoryAttribute ("Appearance")]
641 [DefaultValueAttribute (GridLines.Both)]
642 public virtual GridLines GridLines {
644 object ob = ViewState ["GridLines"];
645 if (ob != null) return (GridLines) ob;
646 return GridLines.Both;
649 ViewState ["GridLines"] = value;
653 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
654 [BrowsableAttribute (false)]
655 public virtual GridViewRow HeaderRow {
657 if (headerRow == null)
658 headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
663 [WebCategoryAttribute ("Styles")]
664 [PersistenceMode (PersistenceMode.InnerProperty)]
665 [NotifyParentProperty (true)]
666 [DefaultValue (null)]
667 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
668 public virtual TableItemStyle HeaderStyle {
670 if (headerStyle == null) {
671 headerStyle = new TableItemStyle ();
672 if (IsTrackingViewState)
673 headerStyle.TrackViewState();
679 [DefaultValueAttribute (HorizontalAlign.NotSet)]
680 public virtual HorizontalAlign HorizontalAlign {
682 object ob = ViewState ["HorizontalAlign"];
683 if (ob != null) return (HorizontalAlign) ob;
684 return HorizontalAlign.NotSet;
687 ViewState ["HorizontalAlign"] = value;
692 [BrowsableAttribute (false)]
693 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
694 public int PageCount {
696 if (pageCount != -1) return pageCount;
702 [WebCategoryAttribute ("Paging")]
703 [BrowsableAttribute (true)]
704 [DefaultValueAttribute (0)]
705 public int PageIndex {
715 [DefaultValueAttribute (10)]
716 [WebCategoryAttribute ("Paging")]
717 public int PageSize {
719 object ob = ViewState ["PageSize"];
720 if (ob != null) return (int) ob;
724 ViewState ["PageSize"] = value;
729 [WebCategoryAttribute ("Paging")]
730 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
731 [NotifyParentPropertyAttribute (true)]
732 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
733 public PagerSettings PagerSettings {
735 if (pagerSettings == null) {
736 pagerSettings = new PagerSettings (this);
737 if (IsTrackingViewState)
738 ((IStateManager)pagerSettings).TrackViewState ();
740 return pagerSettings;
744 [WebCategoryAttribute ("Styles")]
745 [PersistenceMode (PersistenceMode.InnerProperty)]
746 [NotifyParentProperty (true)]
747 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
748 public virtual TableItemStyle PagerStyle {
750 if (pagerStyle == null) {
751 pagerStyle = new TableItemStyle ();
752 if (IsTrackingViewState)
753 pagerStyle.TrackViewState();
760 [DefaultValue (null)]
761 [TemplateContainer (typeof(GridView), BindingDirection.OneWay)]
762 [PersistenceMode (PersistenceMode.InnerProperty)]
764 public ITemplate PagerTemplate {
765 get { return pagerTemplate; }
766 set { pagerTemplate = value; RequireBinding (); }
769 [DefaultValueAttribute ("")]
770 [WebCategoryAttribute ("Accessibility")]
771 // [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
772 public virtual string RowHeaderColumn {
774 object ob = ViewState ["RowHeaderColumn"];
775 if (ob != null) return (string) ob;
779 ViewState ["RowHeaderColumn"] = value;
784 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
785 [BrowsableAttribute (false)]
786 public virtual GridViewRowCollection Rows {
793 [WebCategoryAttribute ("Styles")]
794 [PersistenceMode (PersistenceMode.InnerProperty)]
795 [NotifyParentProperty (true)]
796 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
797 public virtual TableItemStyle RowStyle {
799 if (rowStyle == null) {
800 rowStyle = new TableItemStyle ();
801 if (IsTrackingViewState)
802 rowStyle.TrackViewState();
808 [BrowsableAttribute (false)]
809 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
810 public virtual DataKey SelectedDataKey {
812 if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
813 return DataKeys [selectedIndex];
819 [BindableAttribute (true)]
820 [DefaultValueAttribute (-1)]
821 public int SelectedIndex {
823 return selectedIndex;
826 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
827 int oldIndex = selectedIndex;
829 Rows [oldIndex].RowState = GetRowState (oldIndex);
831 selectedIndex = value;
832 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
833 Rows [selectedIndex].RowState = GetRowState (selectedIndex);
838 [BrowsableAttribute (false)]
839 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
840 public virtual GridViewRow SelectedRow {
842 if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
843 return Rows [selectedIndex];
849 [WebCategoryAttribute ("Styles")]
850 [PersistenceMode (PersistenceMode.InnerProperty)]
851 [NotifyParentProperty (true)]
852 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
853 public virtual TableItemStyle SelectedRowStyle {
855 if (selectedRowStyle == null) {
856 selectedRowStyle = new TableItemStyle ();
857 if (IsTrackingViewState)
858 selectedRowStyle.TrackViewState();
860 return selectedRowStyle;
864 [BrowsableAttribute (false)]
865 public virtual object SelectedValue {
867 if (SelectedDataKey != null)
868 return SelectedDataKey.Value;
874 [WebCategoryAttribute ("Appearance")]
875 [DefaultValueAttribute (false)]
876 public virtual bool ShowFooter {
878 object ob = ViewState ["ShowFooter"];
879 if (ob != null) return (bool) ob;
883 ViewState ["ShowFooter"] = value;
888 [WebCategoryAttribute ("Appearance")]
889 [DefaultValueAttribute (true)]
890 public virtual bool ShowHeader {
892 object ob = ViewState ["ShowHeader"];
893 if (ob != null) return (bool) ob;
897 ViewState ["ShowHeader"] = value;
902 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
903 [BrowsableAttribute (false)]
904 [DefaultValueAttribute (SortDirection.Ascending)]
905 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
906 public virtual SortDirection SortDirection {
907 get { return sortDirection; }
910 [BrowsableAttribute (false)]
911 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
912 public virtual string SortExpression {
913 get { return sortExpression; }
916 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
917 [BrowsableAttribute (false)]
918 public virtual GridViewRow TopPagerRow {
925 [WebCategoryAttribute ("Accessibility")]
926 [DefaultValueAttribute (true)]
927 public virtual bool UseAccessibleHeader {
929 object ob = ViewState ["UseAccessibleHeader"];
930 if (ob != null) return (bool) ob;
934 ViewState ["UseAccessibleHeader"] = value;
939 public virtual bool IsBindableType (Type type)
941 return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Guid);
944 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
946 return base.CreateDataSourceSelectArguments ();
949 protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
951 ArrayList fields = new ArrayList ();
953 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateSelectButton) {
954 CommandField field = new CommandField ();
955 field.ShowEditButton = AutoGenerateEditButton;
956 field.ShowDeleteButton = AutoGenerateDeleteButton;
957 field.ShowSelectButton = AutoGenerateSelectButton;
961 if (AutoGenerateColumns) {
963 autoFieldProperties = CreateAutoFieldProperties (dataSource);
965 if (autoFieldProperties != null) {
966 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
967 fields.Add (CreateAutoGeneratedColumn (props));
971 fields.AddRange (Columns);
976 protected virtual AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
978 return new AutoGeneratedField (fieldProperties);
981 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (PagedDataSource source)
983 if(source == null) return null;
985 PropertyDescriptorCollection props = source.GetItemProperties (new PropertyDescriptor[0]);
988 ArrayList retVal = new ArrayList();
994 PropertyInfo prop_item = source.DataSource.GetType().GetProperty("Item",
995 BindingFlags.Instance | BindingFlags.Static |
996 BindingFlags.Public, null, null,
997 new Type[] { typeof(int) }, null);
999 if (prop_item != null) {
1000 prop_type = prop_item.PropertyType;
1003 if (prop_type == null || prop_type == typeof(object)) {
1004 IEnumerator en = source.GetEnumerator();
1008 prop_type = fitem.GetType();
1011 if (fitem != null && fitem is ICustomTypeDescriptor) {
1012 props = TypeDescriptor.GetProperties(fitem);
1013 } else if (prop_type != null) {
1014 if (IsBindableType (prop_type)) {
1015 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1016 ((IStateManager)field).TrackViewState();
1017 field.Name = "Item";
1018 field.DataField = BoundField.ThisExpression;
1019 field.Type = prop_type;
1022 props = TypeDescriptor.GetProperties (prop_type);
1027 if (props != null && props.Count > 0)
1029 foreach (PropertyDescriptor current in props) {
1030 if (IsBindableType (current.PropertyType)) {
1031 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1032 ((IStateManager)field).TrackViewState();
1033 field.Name = current.Name;
1034 field.DataField = current.Name;
1035 field.IsReadOnly = current.IsReadOnly;
1036 field.Type = current.PropertyType;
1042 if (retVal.Count > 0)
1043 return (AutoGeneratedFieldProperties[]) retVal.ToArray (typeof(AutoGeneratedFieldProperties));
1045 return new AutoGeneratedFieldProperties [0];
1048 protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
1050 GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
1051 OnRowCreated (new GridViewRowEventArgs (row));
1055 void RequireBinding ()
1058 RequiresDataBinding = true;
1063 protected virtual Table CreateChildTable ()
1065 Table table = new Table ();
1066 table.Caption = Caption;
1067 table.CaptionAlign = CaptionAlign;
1068 table.CellPadding = CellPadding;
1069 table.CellSpacing = CellSpacing;
1070 table.HorizontalAlign = HorizontalAlign;
1071 table.BackImageUrl = BackImageUrl;
1075 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1077 PagedDataSource dataSource;
1080 DataSourceView view = GetData ();
1081 dataSource = new PagedDataSource ();
1082 dataSource.DataSource = data;
1085 dataSource.AllowPaging = true;
1086 dataSource.PageSize = PageSize;
1087 dataSource.CurrentPageIndex = PageIndex;
1089 dataSource.AllowServerPaging = true;
1090 if (view.CanRetrieveTotalRowCount)
1091 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1093 dataSource.DataSourceView = view;
1094 dataSource.DataSourceSelectArguments = SelectArguments;
1095 dataSource.SetItemCountFromPageIndex (PageIndex + PagerSettings.PageButtonCount);
1100 pageCount = dataSource.PageCount;
1104 dataSource = new PagedDataSource ();
1105 dataSource.DataSource = data;
1107 dataSource.AllowPaging = true;
1108 dataSource.PageSize = PageSize;
1109 dataSource.CurrentPageIndex = PageIndex;
1113 bool showPager = AllowPaging && (PageCount > 1);
1116 table = CreateChildTable ();
1117 Controls.Add (table);
1119 ArrayList list = new ArrayList ();
1120 ArrayList keyList = new ArrayList ();
1122 // Creates the set of fields to show
1124 ICollection fieldCollection = CreateColumns (dataSource, dataBinding);
1125 DataControlField[] fields = new DataControlField [fieldCollection.Count];
1126 fieldCollection.CopyTo (fields, 0);
1128 foreach (DataControlField field in fields) {
1129 field.Initialize (AllowSorting, this);
1130 if (EnableSortingAndPagingCallbacks)
1131 field.ValidateSupportsCallback ();
1134 // Main table creation
1136 if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
1137 topPagerRow = CreatePagerRow (fields.Length, dataSource);
1138 table.Rows.Add (topPagerRow);
1142 headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
1143 table.Rows.Add (headerRow);
1144 InitializeRow (headerRow, fields);
1147 foreach (object obj in dataSource) {
1148 DataControlRowState rstate = GetRowState (list.Count);
1149 GridViewRow row = CreateRow (list.Count, list.Count, DataControlRowType.DataRow, rstate);
1152 table.Rows.Add (row);
1153 InitializeRow (row, fields);
1156 OnRowDataBound (new GridViewRowEventArgs (row));
1157 if (EditIndex == row.RowIndex)
1158 oldEditValues = new DataKey (GetRowValues (row, false, true));
1159 keyList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
1161 if (EditIndex == row.RowIndex)
1162 oldEditValues = new DataKey (new OrderedDictionary ());
1163 keyList.Add (new DataKey (new OrderedDictionary (), DataKeyNames));
1166 if (list.Count >= PageSize)
1170 if (list.Count == 0)
1171 table.Rows.Add (CreateEmptyrRow (fields.Length));
1174 footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
1175 table.Rows.Add (footerRow);
1176 InitializeRow (footerRow, fields);
1179 if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
1180 bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
1181 table.Rows.Add (bottomPagerRow);
1184 rows = new GridViewRowCollection (list);
1185 keys = new DataKeyArray (keyList);
1187 return dataSource.DataSourceCount;
1190 DataControlRowState GetRowState (int index)
1192 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1193 if (index == SelectedIndex) rstate |= DataControlRowState.Selected;
1194 if (index == EditIndex) rstate |= DataControlRowState.Edit;
1198 GridViewRow CreatePagerRow (int fieldCount, PagedDataSource dataSource)
1200 GridViewRow row = CreateRow (-1, -1, DataControlRowType.Pager, DataControlRowState.Normal);
1201 InitializePager (row, fieldCount, dataSource);
1205 protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
1207 TableCell cell = new TableCell ();
1208 cell.ColumnSpan = columnSpan;
1210 if (pagerTemplate != null)
1211 pagerTemplate.InstantiateIn (cell);
1213 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1215 row.Cells.Add (cell);
1218 GridViewRow CreateEmptyrRow (int fieldCount)
1220 GridViewRow row = CreateRow (-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1221 TableCell cell = new TableCell ();
1222 cell.ColumnSpan = fieldCount;
1224 if (emptyDataTemplate != null)
1225 emptyDataTemplate.InstantiateIn (cell);
1227 cell.Text = EmptyDataText;
1229 row.Cells.Add (cell);
1233 protected virtual void InitializeRow (GridViewRow row, DataControlField[] fields)
1235 DataControlCellType ctype;
1236 bool accessibleHeader = false;
1238 switch (row.RowType) {
1239 case DataControlRowType.Header:
1240 ctype = DataControlCellType.Header;
1241 accessibleHeader = UseAccessibleHeader;
1243 case DataControlRowType.Footer:
1244 ctype = DataControlCellType.Footer;
1247 ctype = DataControlCellType.DataCell;
1251 for (int n=0; n<fields.Length; n++) {
1252 DataControlField field = fields [n];
1253 DataControlFieldCell cell;
1254 if (((field is BoundField) && ((BoundField)field).DataField == RowHeaderColumn) || accessibleHeader)
1255 cell = new DataControlFieldHeaderCell (field, accessibleHeader ? TableHeaderScope.Column : TableHeaderScope.Row);
1257 cell = new DataControlFieldCell (field);
1258 row.Cells.Add (cell);
1259 field.InitializeCell (cell, ctype, row.RowState, row.RowIndex);
1263 IOrderedDictionary CreateRowDataKey (GridViewRow row)
1265 if (cachedKeyProperties == null) {
1266 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (row.DataItem);
1267 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1268 for (int n=0; n<DataKeyNames.Length; n++) {
1269 PropertyDescriptor p = props [DataKeyNames[n]];
1271 new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + row.DataItem.GetType());
1272 cachedKeyProperties [n] = p;
1276 OrderedDictionary dic = new OrderedDictionary ();
1277 foreach (PropertyDescriptor p in cachedKeyProperties)
1278 dic [p.Name] = p.GetValue (row.DataItem);
1282 IOrderedDictionary GetRowValues (GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1284 OrderedDictionary dic = new OrderedDictionary ();
1285 ExtractRowValues (dic, row, includeReadOnlyFields, includePrimaryKey);
1289 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
1291 foreach (TableCell cell in row.Cells) {
1292 DataControlFieldCell c = cell as DataControlFieldCell;
1294 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1296 if (!includePrimaryKey && DataKeyNames != null)
1297 foreach (string key in DataKeyNames)
1298 fieldValues.Remove (key);
1301 protected override HtmlTextWriterTag TagKey {
1303 if (EnableSortingAndPagingCallbacks)
1304 return HtmlTextWriterTag.Div;
1306 return HtmlTextWriterTag.Table;
1310 public sealed override void DataBind ()
1312 DataSourceView view = GetData ();
1313 if (AllowPaging && view.CanPage) {
1314 SelectArguments.StartRowIndex = PageIndex * PageSize;
1315 SelectArguments.MaximumRows = PageSize;
1316 if (view.CanRetrieveTotalRowCount)
1317 SelectArguments.RetrieveTotalRowCount = true;
1320 if (sortExpression != "") {
1321 if (sortDirection == SortDirection.Ascending)
1322 SelectArguments.SortExpression = sortExpression;
1324 SelectArguments.SortExpression = sortExpression + " DESC";
1327 cachedKeyProperties = null;
1331 protected override void PerformDataBinding (IEnumerable data)
1333 base.PerformDataBinding (data);
1336 protected override void OnInit (EventArgs e)
1338 Page.RegisterRequiresControlState (this);
1342 void OnFieldsChanged (object sender, EventArgs args)
1347 protected override void OnDataPropertyChanged ()
1349 base.OnDataPropertyChanged ();
1353 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1355 base.OnDataSourceViewChanged (sender, e);
1359 protected override bool OnBubbleEvent (object source, EventArgs e)
1361 GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
1363 OnRowCommand (args);
1364 ProcessEvent (args.CommandName, args.CommandArgument as string);
1366 return base.OnBubbleEvent (source, e);
1369 // This is prolly obsolete
1370 protected virtual void RaisePostBackEvent (string eventArgument)
1372 int i = eventArgument.IndexOf ('$');
1374 ProcessEvent (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1376 ProcessEvent (eventArgument, null);
1379 void ProcessEvent (string eventName, string param)
1383 case DataControlCommands.PageCommandName:
1386 case DataControlCommands.FirstPageCommandArgument:
1389 case DataControlCommands.LastPageCommandArgument:
1390 newIndex = PageCount - 1;
1392 case DataControlCommands.NextPageCommandArgument:
1393 if (PageIndex < PageCount - 1) newIndex = PageIndex + 1;
1395 case DataControlCommands.PreviousPageCommandArgument:
1396 if (PageIndex > 0) newIndex = PageIndex - 1;
1399 newIndex = int.Parse (param) - 1;
1402 ShowPage (newIndex);
1405 case DataControlCommands.FirstPageCommandArgument:
1409 case DataControlCommands.LastPageCommandArgument:
1410 ShowPage (PageCount - 1);
1413 case DataControlCommands.NextPageCommandArgument:
1414 if (PageIndex < PageCount - 1)
1415 ShowPage (PageIndex + 1);
1418 case DataControlCommands.PreviousPageCommandArgument:
1420 ShowPage (PageIndex - 1);
1423 case DataControlCommands.SelectCommandName:
1424 SelectRow (int.Parse (param));
1427 case DataControlCommands.EditCommandName:
1428 EditRow (int.Parse (param));
1431 case DataControlCommands.UpdateCommandName:
1432 UpdateRow (EditIndex, true);
1435 case DataControlCommands.CancelCommandName:
1439 case DataControlCommands.DeleteCommandName:
1440 DeleteRow (int.Parse (param));
1443 case DataControlCommands.SortCommandName:
1449 void Sort (string newSortExpression)
1451 SortDirection newDirection;
1452 if (sortExpression == newSortExpression) {
1453 if (sortDirection == SortDirection.Ascending)
1454 newDirection = SortDirection.Descending;
1456 newDirection = SortDirection.Ascending;
1458 newDirection = sortDirection;
1460 Sort (newSortExpression, newDirection);
1463 public void Sort (string newSortExpression, SortDirection newSortDirection)
1465 GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
1467 if (args.Cancel) return;
1469 sortExpression = args.SortExpression;
1470 sortDirection = args.SortDirection;
1473 OnSorted (EventArgs.Empty);
1476 void SelectRow (int index)
1478 GridViewSelectEventArgs args = new GridViewSelectEventArgs (index);
1479 OnSelectedIndexChanging (args);
1481 SelectedIndex = args.NewSelectedIndex;
1482 OnSelectedIndexChanged (EventArgs.Empty);
1486 void ShowPage (int newIndex)
1488 GridViewPageEventArgs args = new GridViewPageEventArgs (newIndex);
1489 OnPageIndexChanging (args);
1492 PageIndex = args.NewPageIndex;
1493 OnPageIndexChanged (EventArgs.Empty);
1497 void EditRow (int index)
1499 GridViewEditEventArgs args = new GridViewEditEventArgs (index);
1500 OnRowEditing (args);
1502 EditIndex = args.NewEditIndex;
1508 GridViewCancelEditEventArgs args = new GridViewCancelEditEventArgs (EditIndex);
1509 OnRowCancelingEdit (args);
1515 [MonoTODO ("Support two-way binding expressions")]
1516 public virtual void UpdateRow (int rowIndex, bool causesValidation)
1518 if (causesValidation)
1521 if (rowIndex != EditIndex) throw new NotSupportedException ();
1523 currentEditOldValues = oldEditValues.Values;
1525 GridViewRow row = Rows [rowIndex];
1526 currentEditRowKeys = DataKeys [rowIndex].Values;
1527 currentEditNewValues = GetRowValues (row, false, false);
1529 GridViewUpdateEventArgs args = new GridViewUpdateEventArgs (EditIndex, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1530 OnRowUpdating (args);
1532 DataSourceView view = GetData ();
1533 if (view == null) throw new HttpException ("The DataSourceView associated to data bound control was null");
1534 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1539 bool UpdateCallback (int recordsAffected, Exception exception)
1541 GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1542 OnRowUpdated (dargs);
1544 if (!dargs.KeepInEditMode)
1547 return dargs.ExceptionHandled;
1550 public void DeleteRow (int rowIndex)
1552 GridViewRow row = Rows [rowIndex];
1553 currentEditRowKeys = DataKeys [rowIndex].Values;
1554 currentEditNewValues = GetRowValues (row, true, true);
1556 GridViewDeleteEventArgs args = new GridViewDeleteEventArgs (rowIndex, currentEditRowKeys, currentEditNewValues);
1557 OnRowDeleting (args);
1561 DataSourceView view = GetData ();
1563 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1565 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1566 OnRowDeleted (dargs);
1571 bool DeleteCallback (int recordsAffected, Exception exception)
1573 GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1574 OnRowDeleted (dargs);
1575 return dargs.ExceptionHandled;
1581 oldEditValues = new DataKey (new OrderedDictionary ());
1582 currentEditRowKeys = null;
1583 currentEditOldValues = null;
1584 currentEditNewValues = null;
1587 protected internal override void LoadControlState (object ob)
1589 if (ob == null) return;
1590 object[] state = (object[]) ob;
1591 base.LoadControlState (state[0]);
1592 pageIndex = (int) state[1];
1593 pageCount = (int) state[2];
1594 selectedIndex = (int) state[3];
1595 editIndex = (int) state[4];
1596 sortExpression = (string) state[5];
1597 sortDirection = (SortDirection) state[6];
1600 protected internal override object SaveControlState ()
1602 object bstate = base.SaveControlState ();
1603 return new object[] {
1604 bstate, pageIndex, pageCount, selectedIndex, editIndex, sortExpression, sortDirection
1608 protected override void TrackViewState()
1610 base.TrackViewState();
1611 if (columns != null) ((IStateManager)columns).TrackViewState();
1612 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1613 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1614 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1615 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1616 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1617 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1618 if (selectedRowStyle != null) ((IStateManager)selectedRowStyle).TrackViewState();
1619 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1620 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1621 if (keys != null) ((IStateManager)keys).TrackViewState();
1622 if (autoFieldProperties != null) {
1623 foreach (IStateManager sm in autoFieldProperties)
1624 sm.TrackViewState ();
1628 protected override object SaveViewState()
1630 object[] states = new object [14];
1631 states[0] = base.SaveViewState();
1632 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
1633 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1634 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
1635 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1636 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1637 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1638 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1639 states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
1640 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1641 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1642 states[11] = (keys == null ? null : ((IStateManager)keys).SaveViewState());
1643 states[12] = (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState());
1645 if (autoFieldProperties != null) {
1646 object[] data = new object [autoFieldProperties.Length];
1647 bool allNull = true;
1648 for (int n=0; n<data.Length; n++) {
1649 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
1650 if (data [n] != null) allNull = false;
1652 if (!allNull) states [13] = data;
1655 for (int i = states.Length - 1; i >= 0; i--) {
1656 if (states [i] != null)
1663 protected override void LoadViewState (object savedState)
1665 if (savedState == null) {
1666 base.LoadViewState (null);
1670 object [] states = (object []) savedState;
1672 if (states[13] != null) {
1673 object[] data = (object[]) states [13];
1674 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
1675 for (int n=0; n<data.Length; n++) {
1676 IStateManager p = new AutoGeneratedFieldProperties ();
1677 p.TrackViewState ();
1678 p.LoadViewState (data [n]);
1679 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
1683 base.LoadViewState (states[0]);
1684 EnsureChildControls ();
1686 if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
1687 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1688 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
1689 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1690 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1691 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1692 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1693 if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
1694 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1695 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1696 if (states[11] != null) ((IStateManager)DataKeys).LoadViewState (states[11]);
1697 if (states[12] != null && oldEditValues != null) ((IStateManager)oldEditValues).LoadViewState (states[12]);
1700 string ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
1702 return RaiseCallbackEvent (eventArgs);
1705 protected virtual string RaiseCallbackEvent (string eventArgs)
1707 string[] clientData = eventArgs.Split ('|');
1708 pageIndex = int.Parse (clientData[0]);
1709 sortExpression = HttpUtility.UrlDecode (clientData[1]);
1710 if (sortExpression == "") sortExpression = null;
1713 RaisePostBackEvent (clientData[2]);
1716 StringWriter sw = new StringWriter ();
1717 sw.Write (PageIndex.ToString() + '|' + SortExpression + '|');
1719 HtmlTextWriter writer = new HtmlTextWriter (sw);
1720 RenderGrid (writer);
1721 return sw.ToString ();
1724 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
1726 return GetCallbackScript (control, argument);
1729 protected virtual string GetCallbackScript (IButtonControl control, string argument)
1731 if (EnableSortingAndPagingCallbacks)
1732 return "javascript:GridView_ClientEvent (\"" + ClientID + "\",\"" + control.CommandName + "$" + control.CommandArgument + "\"); return false;";
1737 protected override void OnPreRender (EventArgs e)
1739 base.OnPreRender (e);
1741 if (EnableSortingAndPagingCallbacks)
1743 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(GridView), "GridView.js")) {
1744 string url = Page.ClientScript.GetWebResourceUrl (typeof(GridView), "GridView.js");
1745 Page.ClientScript.RegisterClientScriptInclude (typeof(GridView), "GridView.js", url);
1748 string cgrid = ClientID + "_data";
1749 string script = string.Format ("var {0} = new Object ();\n", cgrid);
1750 script += string.Format ("{0}.pageIndex = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (PageIndex));
1751 script += string.Format ("{0}.sortExp = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression));
1752 script += string.Format ("{0}.uid = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (UniqueID));
1753 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
1755 // Make sure the basic script infrastructure is rendered
1756 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
1757 Page.ClientScript.GetPostBackClientHyperlink (this, "");
1761 protected override void Render (HtmlTextWriter writer)
1763 if (EnableSortingAndPagingCallbacks)
1764 base.RenderBeginTag (writer);
1766 RenderGrid (writer);
1768 if (EnableSortingAndPagingCallbacks)
1769 base.RenderEndTag (writer);
1772 void RenderGrid (HtmlTextWriter writer)
1774 switch (GridLines) {
1775 case GridLines.Horizontal:
1776 writer.AddAttribute (HtmlTextWriterAttribute.Rules, "rows");
1777 writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
1779 case GridLines.Vertical:
1780 writer.AddAttribute (HtmlTextWriterAttribute.Rules, "cols");
1781 writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
1783 case GridLines.Both:
1784 writer.AddAttribute (HtmlTextWriterAttribute.Rules, "all");
1785 writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
1788 writer.AddAttribute (HtmlTextWriterAttribute.Border, "0");
1792 writer.AddAttribute (HtmlTextWriterAttribute.Cellspacing, "0");
1793 writer.AddStyleAttribute (HtmlTextWriterStyle.BorderCollapse, "collapse");
1794 table.RenderBeginTag (writer);
1796 foreach (GridViewRow row in table.Rows)
1798 switch (row.RowType) {
1799 case DataControlRowType.Header:
1800 if (headerStyle != null)headerStyle.AddAttributesToRender (writer, row);
1802 case DataControlRowType.Footer:
1803 if (footerStyle != null) footerStyle.AddAttributesToRender (writer, row);
1805 case DataControlRowType.Pager:
1806 if (pagerStyle != null) pagerStyle.AddAttributesToRender (writer, row);
1808 case DataControlRowType.EmptyDataRow:
1809 if (emptyDataRowStyle != null) emptyDataRowStyle.AddAttributesToRender (writer, row);
1812 if (rowStyle != null) rowStyle.AddAttributesToRender (writer, row);
1816 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null)
1817 alternatingRowStyle.AddAttributesToRender (writer, row);
1818 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null)
1819 editRowStyle.AddAttributesToRender (writer, row);
1820 if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null)
1821 selectedRowStyle.AddAttributesToRender (writer, row);
1823 row.RenderBeginTag (writer);
1825 foreach (TableCell cell in row.Cells) {
1826 DataControlFieldCell fcell = cell as DataControlFieldCell;
1827 if (fcell != null) {
1828 Style cellStyle = null;
1829 switch (row.RowType) {
1830 case DataControlRowType.Header: cellStyle = fcell.ContainingField.HeaderStyle; break;
1831 case DataControlRowType.Footer: cellStyle = fcell.ContainingField.FooterStyle; break;
1832 default: cellStyle = fcell.ContainingField.ItemStyle; break;
1834 if (cellStyle != null)
1835 cellStyle.AddAttributesToRender (writer, cell);
1837 cell.Render (writer);
1839 row.RenderEndTag (writer);
1841 table.RenderEndTag (writer);