2 // System.Web.UI.WebControls.DetailsView.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 [ToolboxDataAttribute ("<{0}:DetailsView runat=\"server\" Width=\"125px\" Height=\"50px\"></{0}:DetailsView>")]
45 [DesignerAttribute ("System.Web.UI.Design.WebControls.DetailsViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
46 [ControlValuePropertyAttribute ("SelectedValue")]
47 [DefaultEventAttribute ("PageIndexChanging")]
48 [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
49 [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
50 public class DetailsView: CompositeDataBoundControl, ICallbackEventHandler, ICallbackContainer, IDataItemContainer, INamingContainer, IPostBackEventHandler, IPostBackContainer
55 DetailsViewRowCollection rows;
56 DetailsViewRow headerRow;
57 DetailsViewRow footerRow;
58 DetailsViewRow bottomPagerRow;
59 DetailsViewRow topPagerRow;
61 IOrderedDictionary currentEditRowKeys;
62 IOrderedDictionary currentEditNewValues;
63 IOrderedDictionary currentEditOldValues;
65 ITemplate pagerTemplate;
66 ITemplate emptyDataTemplate;
67 ITemplate headerTemplate;
68 ITemplate footerTemplate;
70 PropertyDescriptor[] cachedKeyProperties;
71 readonly string[] emptyKeys = new string[0];
72 readonly string unhandledEventExceptionMessage = "The DetailsView '{0}' fired event {1} which wasn't handled.";
75 DataControlFieldCollection columns;
76 PagerSettings pagerSettings;
78 TableItemStyle alternatingRowStyle;
79 TableItemStyle editRowStyle;
80 TableItemStyle insertRowStyle;
81 TableItemStyle emptyDataRowStyle;
82 TableItemStyle footerStyle;
83 TableItemStyle headerStyle;
84 TableItemStyle pagerStyle;
85 TableItemStyle rowStyle;
86 TableItemStyle commandRowStyle;
87 TableItemStyle fieldHeaderStyle;
89 IOrderedDictionary _keyTable;
91 DataKey oldEditValues;
92 AutoGeneratedFieldProperties[] autoFieldProperties;
94 static readonly object PageIndexChangedEvent = new object();
95 static readonly object PageIndexChangingEvent = new object();
96 static readonly object ItemCommandEvent = new object();
97 static readonly object ItemCreatedEvent = new object();
98 static readonly object ItemDeletedEvent = new object();
99 static readonly object ItemDeletingEvent = new object();
100 static readonly object ItemInsertedEvent = new object();
101 static readonly object ItemInsertingEvent = new object();
102 static readonly object ModeChangingEvent = new object();
103 static readonly object ModeChangedEvent = new object();
104 static readonly object ItemUpdatedEvent = new object();
105 static readonly object ItemUpdatingEvent = new object();
109 DetailsViewMode currentMode = DetailsViewMode.ReadOnly;
113 public DetailsView ()
115 rows = new DetailsViewRowCollection (new ArrayList ());
118 public event EventHandler PageIndexChanged {
119 add { Events.AddHandler (PageIndexChangedEvent, value); }
120 remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
123 public event DetailsViewPageEventHandler PageIndexChanging {
124 add { Events.AddHandler (PageIndexChangingEvent, value); }
125 remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
128 public event DetailsViewCommandEventHandler ItemCommand {
129 add { Events.AddHandler (ItemCommandEvent, value); }
130 remove { Events.RemoveHandler (ItemCommandEvent, value); }
133 public event EventHandler ItemCreated {
134 add { Events.AddHandler (ItemCreatedEvent, value); }
135 remove { Events.RemoveHandler (ItemCreatedEvent, value); }
138 public event DetailsViewDeletedEventHandler ItemDeleted {
139 add { Events.AddHandler (ItemDeletedEvent, value); }
140 remove { Events.RemoveHandler (ItemDeletedEvent, value); }
143 public event DetailsViewDeleteEventHandler ItemDeleting {
144 add { Events.AddHandler (ItemDeletingEvent, value); }
145 remove { Events.RemoveHandler (ItemDeletingEvent, value); }
148 public event DetailsViewInsertedEventHandler ItemInserted {
149 add { Events.AddHandler (ItemInsertedEvent, value); }
150 remove { Events.RemoveHandler (ItemInsertedEvent, value); }
153 public event DetailsViewInsertEventHandler ItemInserting {
154 add { Events.AddHandler (ItemInsertingEvent, value); }
155 remove { Events.RemoveHandler (ItemInsertingEvent, value); }
158 public event DetailsViewModeEventHandler ModeChanging {
159 add { Events.AddHandler (ModeChangingEvent, value); }
160 remove { Events.RemoveHandler (ModeChangingEvent, value); }
163 public event EventHandler ModeChanged {
164 add { Events.AddHandler (ModeChangedEvent, value); }
165 remove { Events.RemoveHandler (ModeChangedEvent, value); }
168 public event DetailsViewUpdatedEventHandler ItemUpdated {
169 add { Events.AddHandler (ItemUpdatedEvent, value); }
170 remove { Events.RemoveHandler (ItemUpdatedEvent, value); }
173 public event DetailsViewUpdateEventHandler ItemUpdating {
174 add { Events.AddHandler (ItemUpdatingEvent, value); }
175 remove { Events.RemoveHandler (ItemUpdatingEvent, value); }
178 protected virtual void OnPageIndexChanged (EventArgs e)
180 if (Events != null) {
181 EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
182 if (eh != null) eh (this, e);
186 protected virtual void OnPageIndexChanging (DetailsViewPageEventArgs e)
188 if (Events != null) {
189 DetailsViewPageEventHandler eh = (DetailsViewPageEventHandler) Events [PageIndexChangingEvent];
195 if (!IsBoundUsingDataSourceID)
196 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "PageIndexChanging"));
199 protected virtual void OnItemCommand (DetailsViewCommandEventArgs e)
201 if (Events != null) {
202 DetailsViewCommandEventHandler eh = (DetailsViewCommandEventHandler) Events [ItemCommandEvent];
203 if (eh != null) eh (this, e);
207 protected virtual void OnItemCreated (EventArgs e)
209 if (Events != null) {
210 EventHandler eh = (EventHandler) Events [ItemCreatedEvent];
211 if (eh != null) eh (this, e);
215 protected virtual void OnItemDeleted (DetailsViewDeletedEventArgs e)
217 if (Events != null) {
218 DetailsViewDeletedEventHandler eh = (DetailsViewDeletedEventHandler) Events [ItemDeletedEvent];
219 if (eh != null) eh (this, e);
223 protected virtual void OnItemInserted (DetailsViewInsertedEventArgs e)
225 if (Events != null) {
226 DetailsViewInsertedEventHandler eh = (DetailsViewInsertedEventHandler) Events [ItemInsertedEvent];
227 if (eh != null) eh (this, e);
231 protected virtual void OnItemInserting (DetailsViewInsertEventArgs e)
233 if (Events != null) {
234 DetailsViewInsertEventHandler eh = (DetailsViewInsertEventHandler) Events [ItemInsertingEvent];
240 if (!IsBoundUsingDataSourceID)
241 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ItemInserting"));
244 protected virtual void OnItemDeleting (DetailsViewDeleteEventArgs e)
246 if (Events != null) {
247 DetailsViewDeleteEventHandler eh = (DetailsViewDeleteEventHandler) Events [ItemDeletingEvent];
253 if (!IsBoundUsingDataSourceID)
254 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ItemDeleting"));
257 protected virtual void OnModeChanged (EventArgs e)
259 if (Events != null) {
260 EventHandler eh = (EventHandler) Events [ModeChangedEvent];
261 if (eh != null) eh (this, e);
265 protected virtual void OnModeChanging (DetailsViewModeEventArgs e)
267 if (Events != null) {
268 DetailsViewModeEventHandler eh = (DetailsViewModeEventHandler) Events [ModeChangingEvent];
274 if (!IsBoundUsingDataSourceID)
275 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ModeChanging"));
278 protected virtual void OnItemUpdated (DetailsViewUpdatedEventArgs e)
280 if (Events != null) {
281 DetailsViewUpdatedEventHandler eh = (DetailsViewUpdatedEventHandler) Events [ItemUpdatedEvent];
282 if (eh != null) eh (this, e);
286 protected virtual void OnItemUpdating (DetailsViewUpdateEventArgs e)
288 if (Events != null) {
289 DetailsViewUpdateEventHandler eh = (DetailsViewUpdateEventHandler) Events [ItemUpdatingEvent];
295 if (!IsBoundUsingDataSourceID)
296 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ItemUpdating"));
300 [WebCategoryAttribute ("Paging")]
301 [DefaultValueAttribute (false)]
302 public virtual bool AllowPaging {
304 object ob = ViewState ["AllowPaging"];
305 if (ob != null) return (bool) ob;
309 ViewState ["AllowPaging"] = value;
314 [DefaultValueAttribute (null)]
315 [WebCategoryAttribute ("Styles")]
316 [PersistenceMode (PersistenceMode.InnerProperty)]
317 [NotifyParentProperty (true)]
318 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
319 public TableItemStyle AlternatingRowStyle {
321 if (alternatingRowStyle == null) {
322 alternatingRowStyle = new TableItemStyle ();
323 if (IsTrackingViewState)
324 alternatingRowStyle.TrackViewState();
326 return alternatingRowStyle;
330 [WebCategoryAttribute ("Behavior")]
331 [DefaultValueAttribute (false)]
332 public virtual bool AutoGenerateEditButton {
334 object ob = ViewState ["AutoGenerateEditButton"];
335 if (ob != null) return (bool) ob;
339 ViewState ["AutoGenerateEditButton"] = value;
344 [WebCategoryAttribute ("Behavior")]
345 [DefaultValueAttribute (false)]
346 public virtual bool AutoGenerateDeleteButton {
348 object ob = ViewState ["AutoGenerateDeleteButton"];
349 if (ob != null) return (bool) ob;
353 ViewState ["AutoGenerateDeleteButton"] = value;
358 [WebCategoryAttribute ("Behavior")]
359 [DefaultValueAttribute (false)]
360 public virtual bool AutoGenerateInsertButton {
362 object ob = ViewState ["AutoGenerateInsertButton"];
363 if (ob != null) return (bool) ob;
367 ViewState ["AutoGenerateInsertButton"] = value;
372 [WebCategoryAttribute ("Behavior")]
373 [DefaultValueAttribute (true)]
374 public virtual bool AutoGenerateRows {
376 object ob = ViewState ["AutoGenerateRows"];
377 if (ob != null) return (bool) ob;
381 ViewState ["AutoGenerateRows"] = value;
386 [UrlPropertyAttribute]
387 [WebCategoryAttribute ("Appearance")]
388 [DefaultValueAttribute ("")]
389 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
390 public virtual string BackImageUrl {
392 if (ControlStyleCreated)
393 return ((TableStyle) ControlStyle).BackImageUrl;
397 ((TableStyle) ControlStyle).BackImageUrl = value;
401 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
402 [BrowsableAttribute (false)]
403 public virtual DetailsViewRow BottomPagerRow {
405 EnsureChildControls ();
406 return bottomPagerRow;
410 [WebCategoryAttribute ("Accessibility")]
411 [DefaultValueAttribute ("")]
412 [LocalizableAttribute (true)]
413 public virtual string Caption {
415 object ob = ViewState ["Caption"];
416 if (ob != null) return (string) ob;
420 ViewState ["Caption"] = value;
425 [WebCategoryAttribute ("Accessibility")]
426 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
427 public virtual TableCaptionAlign CaptionAlign
430 object o = ViewState ["CaptionAlign"];
431 if(o != null) return (TableCaptionAlign) o;
432 return TableCaptionAlign.NotSet;
435 ViewState ["CaptionAlign"] = value;
440 [WebCategoryAttribute ("Layout")]
441 [DefaultValueAttribute (-1)]
442 public virtual int CellPadding
445 if (ControlStyleCreated)
446 return ((TableStyle) ControlStyle).CellPadding;
450 ((TableStyle) ControlStyle).CellPadding = value;
454 [WebCategoryAttribute ("Layout")]
455 [DefaultValueAttribute (0)]
456 public virtual int CellSpacing
459 if (ControlStyleCreated)
460 return ((TableStyle) ControlStyle).CellSpacing;
464 ((TableStyle) ControlStyle).CellSpacing = value;
468 [DefaultValueAttribute (null)]
469 [WebCategoryAttribute ("Styles")]
470 [PersistenceMode (PersistenceMode.InnerProperty)]
471 [NotifyParentProperty (true)]
472 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
473 public TableItemStyle CommandRowStyle {
475 if (commandRowStyle == null) {
476 commandRowStyle = new TableItemStyle ();
477 if (IsTrackingViewState)
478 commandRowStyle.TrackViewState();
480 return commandRowStyle;
484 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
485 [BrowsableAttribute (false)]
486 public DetailsViewMode CurrentMode {
488 return hasCurrentMode ? currentMode : DefaultMode;
491 hasCurrentMode = true;
496 DetailsViewMode defaultMode = DetailsViewMode.ReadOnly;
497 [DefaultValueAttribute (DetailsViewMode.ReadOnly)]
498 [WebCategoryAttribute ("Behavior")]
499 public virtual DetailsViewMode DefaultMode {
509 [EditorAttribute ("System.Web.UI.Design.WebControls.DataControlFieldTypeEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
510 [MergablePropertyAttribute (false)]
511 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
512 [DefaultValueAttribute (null)]
513 [WebCategoryAttribute ("Misc")]
514 public virtual DataControlFieldCollection Fields {
516 if (columns == null) {
517 columns = new DataControlFieldCollection ();
518 columns.FieldsChanged += new EventHandler (OnFieldsChanged);
519 if (IsTrackingViewState)
520 ((IStateManager)columns).TrackViewState ();
526 string[] dataKeyNames = null;
528 [DefaultValueAttribute (null)]
529 [WebCategoryAttribute ("Data")]
530 [TypeConverter (typeof(StringArrayConverter))]
531 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
532 public virtual string[] DataKeyNames
535 if (dataKeyNames == null)
541 dataKeyNames = value;
546 IOrderedDictionary KeyTable {
548 if (_keyTable == null) {
549 _keyTable = new OrderedDictionary (DataKeyNames.Length);
555 [BrowsableAttribute (false)]
556 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
557 public virtual DataKey DataKey {
560 key = new DataKey (KeyTable);
566 DataKey OldEditValues {
568 if (oldEditValues == null) {
569 oldEditValues = new DataKey (new OrderedDictionary ());
571 return oldEditValues;
575 [WebCategoryAttribute ("Styles")]
576 [PersistenceMode (PersistenceMode.InnerProperty)]
577 [NotifyParentProperty (true)]
578 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
579 [DefaultValueAttribute (null)]
580 public TableItemStyle EditRowStyle {
582 if (editRowStyle == null) {
583 editRowStyle = new TableItemStyle ();
584 if (IsTrackingViewState)
585 editRowStyle.TrackViewState();
591 [WebCategoryAttribute ("Styles")]
592 [PersistenceMode (PersistenceMode.InnerProperty)]
593 [NotifyParentProperty (true)]
594 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
595 [DefaultValueAttribute (null)]
596 public TableItemStyle EmptyDataRowStyle {
598 if (emptyDataRowStyle == null) {
599 emptyDataRowStyle = new TableItemStyle ();
600 if (IsTrackingViewState)
601 emptyDataRowStyle.TrackViewState();
603 return emptyDataRowStyle;
607 [DefaultValue (null)]
608 [TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
609 [PersistenceMode (PersistenceMode.InnerProperty)]
611 public virtual ITemplate EmptyDataTemplate {
612 get { return emptyDataTemplate; }
613 set { emptyDataTemplate = value; }
616 [LocalizableAttribute (true)]
617 [WebCategoryAttribute ("Appearance")]
618 [DefaultValueAttribute ("")]
619 public virtual string EmptyDataText {
621 object ob = ViewState ["EmptyDataText"];
622 if (ob != null) return (string) ob;
626 ViewState ["EmptyDataText"] = value;
631 [WebCategoryAttribute ("Behavior")]
632 [DefaultValueAttribute (false)]
633 public virtual bool EnablePagingCallbacks {
635 object ob = ViewState ["EnablePagingCallbacks"];
636 if (ob != null) return (bool) ob;
640 ViewState ["EnablePagingCallbacks"] = value;
645 [WebCategoryAttribute ("Styles")]
646 [PersistenceMode (PersistenceMode.InnerProperty)]
647 [NotifyParentProperty (true)]
648 [DefaultValue (null)]
649 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
650 public TableItemStyle FieldHeaderStyle {
652 if (fieldHeaderStyle == null) {
653 fieldHeaderStyle = new TableItemStyle ();
654 if (IsTrackingViewState)
655 fieldHeaderStyle.TrackViewState();
657 return fieldHeaderStyle;
661 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
662 [BrowsableAttribute (false)]
663 public virtual DetailsViewRow FooterRow {
665 EnsureChildControls ();
670 [DefaultValue (null)]
671 [TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
672 [PersistenceMode (PersistenceMode.InnerProperty)]
674 public virtual ITemplate FooterTemplate {
675 get { return footerTemplate; }
676 set { footerTemplate = value; }
679 [LocalizableAttribute (true)]
680 [WebCategoryAttribute ("Appearance")]
681 [DefaultValueAttribute ("")]
682 public virtual string FooterText {
684 object ob = ViewState ["FooterText"];
685 if (ob != null) return (string) ob;
689 ViewState ["FooterText"] = value;
694 [WebCategoryAttribute ("Styles")]
695 [PersistenceMode (PersistenceMode.InnerProperty)]
696 [NotifyParentProperty (true)]
697 [DefaultValue (null)]
698 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
699 public TableItemStyle FooterStyle {
701 if (footerStyle == null) {
702 footerStyle = new TableItemStyle ();
703 if (IsTrackingViewState)
704 footerStyle.TrackViewState();
710 [WebCategoryAttribute ("Appearance")]
711 [DefaultValueAttribute (GridLines.Both)]
712 public virtual GridLines GridLines {
714 if (ControlStyleCreated)
715 return ((TableStyle) ControlStyle).GridLines;
716 return GridLines.Both;
719 ((TableStyle) ControlStyle).GridLines = value;
723 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
724 [BrowsableAttribute (false)]
725 public virtual DetailsViewRow HeaderRow {
727 EnsureChildControls ();
732 [WebCategoryAttribute ("Styles")]
733 [PersistenceMode (PersistenceMode.InnerProperty)]
734 [NotifyParentProperty (true)]
735 [DefaultValue (null)]
736 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
737 public TableItemStyle HeaderStyle {
739 if (headerStyle == null) {
740 headerStyle = new TableItemStyle ();
741 if (IsTrackingViewState)
742 headerStyle.TrackViewState();
748 [DefaultValue (null)]
749 [TemplateContainer (typeof(DetailsView), BindingDirection.OneWay)]
750 [PersistenceMode (PersistenceMode.InnerProperty)]
752 public virtual ITemplate HeaderTemplate {
753 get { return headerTemplate; }
754 set { headerTemplate = value; }
757 [LocalizableAttribute (true)]
758 [WebCategoryAttribute ("Appearance")]
759 [DefaultValueAttribute ("")]
760 public virtual string HeaderText {
762 object ob = ViewState ["HeaderText"];
763 if (ob != null) return (string) ob;
767 ViewState ["HeaderText"] = value;
772 [Category ("Layout")]
773 [DefaultValueAttribute (HorizontalAlign.NotSet)]
774 public virtual HorizontalAlign HorizontalAlign {
776 if (ControlStyleCreated)
777 return ((TableStyle) ControlStyle).HorizontalAlign;
778 return HorizontalAlign.NotSet;
781 ((TableStyle) ControlStyle).HorizontalAlign = value;
785 [WebCategoryAttribute ("Styles")]
786 [PersistenceMode (PersistenceMode.InnerProperty)]
787 [NotifyParentProperty (true)]
788 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
789 [DefaultValueAttribute (null)]
790 public TableItemStyle InsertRowStyle {
792 if (insertRowStyle == null) {
793 insertRowStyle = new TableItemStyle ();
794 if (IsTrackingViewState)
795 insertRowStyle.TrackViewState();
797 return insertRowStyle;
801 [BrowsableAttribute (false)]
802 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
803 public virtual int PageCount {
812 [WebCategoryAttribute ("Paging")]
813 [BindableAttribute (true, BindingDirection.OneWay)]
814 [DefaultValueAttribute (0)]
815 public virtual int PageIndex {
817 if (CurrentMode == DetailsViewMode.Insert)
823 throw new ArgumentOutOfRangeException ("PageIndex must be non-negative");
824 if (pageIndex == value || value == -1)
831 [WebCategoryAttribute ("Paging")]
832 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
833 [NotifyParentPropertyAttribute (true)]
834 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
835 public virtual PagerSettings PagerSettings {
837 if (pagerSettings == null) {
838 pagerSettings = new PagerSettings (this);
839 if (IsTrackingViewState)
840 ((IStateManager)pagerSettings).TrackViewState ();
842 return pagerSettings;
846 [WebCategoryAttribute ("Styles")]
847 [PersistenceMode (PersistenceMode.InnerProperty)]
848 [NotifyParentProperty (true)]
849 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
850 public TableItemStyle PagerStyle {
852 if (pagerStyle == null) {
853 pagerStyle = new TableItemStyle ();
854 if (IsTrackingViewState)
855 pagerStyle.TrackViewState();
862 [DefaultValue (null)]
863 [TemplateContainer (typeof (DetailsView), BindingDirection.OneWay)]
864 [PersistenceMode (PersistenceMode.InnerProperty)]
866 public virtual ITemplate PagerTemplate {
867 get { return pagerTemplate; }
868 set { pagerTemplate = value; }
871 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
872 [BrowsableAttribute (false)]
873 public virtual DetailsViewRowCollection Rows {
875 EnsureChildControls ();
880 [WebCategoryAttribute ("Styles")]
881 [PersistenceMode (PersistenceMode.InnerProperty)]
882 [NotifyParentProperty (true)]
883 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
884 [DefaultValue (null)]
885 public TableItemStyle RowStyle {
887 if (rowStyle == null) {
888 rowStyle = new TableItemStyle ();
889 if (IsTrackingViewState)
890 rowStyle.TrackViewState();
896 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
897 [BrowsableAttribute (false)]
898 public object SelectedValue {
899 get { return DataKey.Value; }
902 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
903 [BrowsableAttribute (false)]
904 public virtual DetailsViewRow TopPagerRow {
906 EnsureChildControls ();
911 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
912 [BrowsableAttribute (false)]
913 public virtual object DataItem {
919 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
920 [BrowsableAttribute (false)]
921 public int DataItemCount {
922 get { return PageCount; }
925 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
926 [BrowsableAttribute (false)]
927 public virtual int DataItemIndex {
928 get { return PageIndex; }
931 int IDataItemContainer.DisplayIndex {
932 get { return PageIndex; }
935 int IDataItemContainer.DataItemIndex {
936 get { return DataItemIndex; }
939 public virtual bool IsBindableType (Type type)
941 return type.IsPrimitive || type == typeof (string) || type == typeof (DateTime) || type == typeof (Guid) || type == typeof (Decimal);
944 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
946 DataSourceSelectArguments arg = new DataSourceSelectArguments ();
947 DataSourceView view = GetData ();
948 if (AllowPaging && view.CanPage) {
949 arg.StartRowIndex = PageIndex;
950 if (view.CanRetrieveTotalRowCount) {
951 arg.RetrieveTotalRowCount = true;
955 arg.MaximumRows = -1;
961 protected virtual ICollection CreateFieldSet (object dataItem, bool useDataSource)
963 ArrayList fields = new ArrayList ();
965 if (AutoGenerateRows) {
967 if (dataItem != null)
968 fields.AddRange (CreateAutoGeneratedRows (dataItem));
970 if (autoFieldProperties != null) {
971 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
972 fields.Add (CreateAutoGeneratedRow (props));
977 fields.AddRange (Fields);
979 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateInsertButton) {
980 CommandField field = new CommandField ();
981 field.ShowEditButton = AutoGenerateEditButton;
982 field.ShowDeleteButton = AutoGenerateDeleteButton;
983 field.ShowInsertButton = AutoGenerateInsertButton;
990 protected virtual ICollection CreateAutoGeneratedRows (object dataItem)
992 if (dataItem == null)
995 ArrayList list = new ArrayList ();
996 autoFieldProperties = CreateAutoFieldProperties (dataItem);
997 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
998 list.Add (CreateAutoGeneratedRow (props));
1002 protected virtual AutoGeneratedField CreateAutoGeneratedRow (AutoGeneratedFieldProperties fieldProperties)
1004 return new AutoGeneratedField (fieldProperties);
1007 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (object dataItem)
1009 if (IsBindableType (dataItem.GetType ()))
1011 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1012 ((IStateManager) field).TrackViewState ();
1013 field.Name = "Item";
1014 field.DataField = BoundField.ThisExpression;
1015 field.Type = dataItem.GetType ();
1016 return new AutoGeneratedFieldProperties [] { field };
1019 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem, false);
1021 if (props != null && props.Count > 0) {
1022 ArrayList retVal = new ArrayList ();
1023 foreach (PropertyDescriptor current in props) {
1024 if (IsBindableType (current.PropertyType)) {
1025 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1026 ((IStateManager) field).TrackViewState ();
1027 field.Name = current.Name;
1028 field.DataField = current.Name;
1029 for (int i = 0; i < DataKeyNames.Length; i++) {
1030 if (string.Compare (DataKeyNames [i], current.Name, StringComparison.InvariantCultureIgnoreCase) == 0) {
1031 field.IsReadOnly = true;
1035 field.Type = current.PropertyType;
1039 if (retVal.Count > 0)
1040 return (AutoGeneratedFieldProperties []) retVal.ToArray (typeof (AutoGeneratedFieldProperties));
1042 throw new HttpException (String.Format ("DetailsView with id '{0}' did not have any properties or attributes from which to generate fields. Ensure that your data source has content.", ID));
1045 protected virtual DetailsViewRow CreateRow (int rowIndex, DataControlRowType rowType, DataControlRowState rowState)
1048 if (rowType == DataControlRowType.Pager)
1049 row = new DetailsViewPagerRow (rowIndex, rowType, rowState);
1051 row = new DetailsViewRow (rowIndex, rowType, rowState);
1055 void RequireBinding ()
1058 RequiresDataBinding = true;
1062 protected virtual Table CreateTable ()
1064 return new ContainedTable (this);
1067 protected override Style CreateControlStyle ()
1069 TableStyle style = new TableStyle ();
1070 style.GridLines = GridLines.Both;
1071 style.CellSpacing = 0;
1075 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1077 PagedDataSource dataSource = new PagedDataSource ();
1078 dataSource.DataSource = CurrentMode != DetailsViewMode.Insert ? data : null;
1079 dataSource.AllowPaging = AllowPaging;
1080 dataSource.PageSize = 1;
1081 dataSource.CurrentPageIndex = PageIndex;
1083 if (dataBinding && CurrentMode != DetailsViewMode.Insert) {
1084 DataSourceView view = GetData ();
1085 if (view != null && view.CanPage) {
1086 dataSource.AllowServerPaging = true;
1087 if (SelectArguments.RetrieveTotalRowCount)
1088 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1092 bool showPager = AllowPaging && (dataSource.PageCount > 1);
1095 table = CreateTable ();
1096 Controls.Add (table);
1100 bottomPagerRow = null;
1101 ArrayList list = new ArrayList ();
1103 // Gets the current data item
1106 PageCount = dataSource.DataSourceCount;
1107 if (PageIndex >= PageCount && PageCount > 0) {
1108 pageIndex = dataSource.CurrentPageIndex = PageCount - 1;
1110 if (dataSource.DataSource != null) {
1111 IEnumerator e = dataSource.GetEnumerator ();
1113 dataItem = e.Current;
1118 object lastItem = null;
1119 if (dataSource.DataSource != null) {
1120 IEnumerator e = dataSource.GetEnumerator ();
1121 for (; e.MoveNext (); page++) {
1122 lastItem = e.Current;
1123 if (page == PageIndex)
1124 dataItem = e.Current;
1128 if (PageIndex >= PageCount && PageCount > 0) {
1129 pageIndex = PageCount - 1;
1130 dataItem = lastItem;
1134 if (PageCount == 0 && CurrentMode != DetailsViewMode.Insert) {
1135 DetailsViewRow row = CreateEmptyRow ();
1137 table.Rows.Add (row);
1143 // Creates the set of fields to show
1145 ICollection fieldCollection = CreateFieldSet (dataItem, dataBinding && dataItem != null);
1146 DataControlField [] fields = new DataControlField [fieldCollection.Count];
1147 fieldCollection.CopyTo (fields, 0);
1149 foreach (DataControlField field in fields) {
1150 field.Initialize (false, this);
1151 if (EnablePagingCallbacks)
1152 field.ValidateSupportsCallback ();
1155 // Main table creation
1157 headerRow = CreateRow (-1, DataControlRowType.Header, DataControlRowState.Normal);
1158 DataControlFieldCell headerCell = new DataControlFieldCell (null);
1159 headerCell.ColumnSpan = 2;
1160 if (headerTemplate != null)
1161 headerTemplate.InstantiateIn (headerCell);
1162 else if (!String.IsNullOrEmpty (HeaderText))
1163 headerCell.Text = HeaderText;
1165 headerRow.Visible = false;
1166 headerRow.Cells.Add (headerCell);
1167 table.Rows.Add (headerRow);
1169 if (showPager && PagerSettings.Position == PagerPosition.Top ||
1170 PagerSettings.Position == PagerPosition.TopAndBottom) {
1171 topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
1172 InitializePager (topPagerRow, dataSource);
1173 table.Rows.Add (topPagerRow);
1176 foreach (DataControlField field in fields) {
1177 DataControlRowState rstate = GetRowState (list.Count);
1178 DetailsViewRow row = CreateRow (PageIndex, DataControlRowType.DataRow, rstate);
1179 InitializeRow (row, field);
1180 table.Rows.Add (row);
1184 footerRow = CreateRow (-1, DataControlRowType.Footer, DataControlRowState.Normal);
1185 DataControlFieldCell footerCell = new DataControlFieldCell (null);
1186 footerCell.ColumnSpan = 2;
1187 if (footerTemplate != null)
1188 footerTemplate.InstantiateIn (footerCell);
1189 else if (!String.IsNullOrEmpty (FooterText))
1190 footerCell.Text = FooterText;
1192 footerRow.Visible = false;
1193 footerRow.Cells.Add (footerCell);
1194 table.Rows.Add (footerRow);
1196 if (showPager && PagerSettings.Position == PagerPosition.Bottom ||
1197 PagerSettings.Position == PagerPosition.TopAndBottom) {
1198 bottomPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
1199 InitializePager (bottomPagerRow, dataSource);
1200 table.Rows.Add (bottomPagerRow);
1204 rows = new DetailsViewRowCollection (list);
1209 OnItemCreated (EventArgs.Empty);
1214 protected override void EnsureDataBound ()
1216 if (CurrentMode == DetailsViewMode.Insert) {
1217 if (RequiresDataBinding) {
1218 OnDataBinding (EventArgs.Empty);
1219 RequiresDataBinding = false;
1220 InternalPerformDataBinding (null);
1222 OnDataBound (EventArgs.Empty);
1226 base.EnsureDataBound ();
1229 DataControlRowState GetRowState (int index)
1231 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1232 if (CurrentMode == DetailsViewMode.Edit) rstate |= DataControlRowState.Edit;
1233 else if (CurrentMode == DetailsViewMode.Insert) rstate |= DataControlRowState.Insert;
1237 protected virtual void InitializePager (DetailsViewRow row, PagedDataSource dataSource)
1239 TableCell cell = new TableCell ();
1240 cell.ColumnSpan = 2;
1242 if (pagerTemplate != null)
1243 pagerTemplate.InstantiateIn (cell);
1245 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1247 row.Cells.Add (cell);
1250 DetailsViewRow CreateEmptyRow ()
1252 TableCell cell = new TableCell ();
1254 if (emptyDataTemplate != null)
1255 emptyDataTemplate.InstantiateIn (cell);
1256 else if (!String.IsNullOrEmpty (EmptyDataText))
1257 cell.Text = EmptyDataText;
1261 DetailsViewRow row = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1262 row.Cells.Add (cell);
1266 protected virtual void InitializeRow (DetailsViewRow row, DataControlField field)
1268 if (!field.Visible) {
1269 row.Visible = false;
1273 row.ContainingField = field;
1274 DataControlFieldCell cell;
1276 if (field.ShowHeader) {
1277 cell = new DataControlFieldCell (field);
1278 row.Cells.Add (cell);
1279 field.InitializeCell (cell, DataControlCellType.Header, row.RowState, row.RowIndex);
1282 cell = new DataControlFieldCell (field);
1283 if (!field.ShowHeader)
1284 cell.ColumnSpan = 2;
1285 row.Cells.Add (cell);
1286 field.InitializeCell (cell, DataControlCellType.DataCell, row.RowState, row.RowIndex);
1288 if (CurrentMode == DetailsViewMode.Insert && !field.InsertVisible)
1289 row.Visible = false;
1292 void FillRowDataKey (object dataItem)
1296 if (cachedKeyProperties == null) {
1297 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
1298 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1299 for (int n=0; n<DataKeyNames.Length; n++) {
1300 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1302 throw new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + dataItem.GetType());
1303 cachedKeyProperties [n] = p;
1307 foreach (PropertyDescriptor p in cachedKeyProperties)
1308 KeyTable [p.Name] = p.GetValue (dataItem);
1311 IOrderedDictionary GetRowValues (bool includeReadOnlyFields, bool includePrimaryKey)
1313 OrderedDictionary dic = new OrderedDictionary ();
1314 ExtractRowValues (dic, includeReadOnlyFields, includePrimaryKey);
1318 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, bool includeReadOnlyFields, bool includePrimaryKey)
1320 foreach (DetailsViewRow row in Rows) {
1321 if (row.Cells.Count < 1) continue;
1322 DataControlFieldCell c = row.Cells[row.Cells.Count-1] as DataControlFieldCell;
1324 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1326 if (!includePrimaryKey && DataKeyNames != null)
1327 foreach (string key in DataKeyNames)
1328 fieldValues.Remove (key);
1331 protected override HtmlTextWriterTag TagKey {
1333 if (EnablePagingCallbacks)
1334 return HtmlTextWriterTag.Div;
1336 return HtmlTextWriterTag.Table;
1340 public sealed override void DataBind ()
1342 cachedKeyProperties = null;
1345 if (dataItem != null) {
1346 if (CurrentMode == DetailsViewMode.Edit)
1347 oldEditValues = new DataKey (GetRowValues (false, true));
1348 FillRowDataKey (dataItem);
1349 key = new DataKey (KeyTable);
1353 protected internal override void PerformDataBinding (IEnumerable data)
1355 base.PerformDataBinding (data);
1358 protected internal virtual void PrepareControlHierarchy ()
1363 table.Caption = Caption;
1364 table.CaptionAlign = CaptionAlign;
1366 foreach (DetailsViewRow row in table.Rows) {
1367 switch (row.RowType) {
1368 case DataControlRowType.Header:
1369 if (headerStyle != null && !headerStyle.IsEmpty)
1370 row.ControlStyle.CopyFrom (headerStyle);
1372 case DataControlRowType.Footer:
1373 if (footerStyle != null && !footerStyle.IsEmpty)
1374 row.ControlStyle.CopyFrom (footerStyle);
1376 case DataControlRowType.Pager:
1377 if (pagerStyle != null && !pagerStyle.IsEmpty)
1378 row.ControlStyle.CopyFrom (pagerStyle);
1380 case DataControlRowType.EmptyDataRow:
1381 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1382 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1384 case DataControlRowType.DataRow:
1385 if (rowStyle != null && !rowStyle.IsEmpty)
1386 row.ControlStyle.CopyFrom (rowStyle);
1387 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1388 row.ControlStyle.CopyFrom (alternatingRowStyle);
1394 if (row.ContainingField is CommandField) {
1395 if (commandRowStyle != null && !commandRowStyle.IsEmpty)
1396 row.ControlStyle.CopyFrom (commandRowStyle);
1399 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1400 row.ControlStyle.CopyFrom (editRowStyle);
1401 if ((row.RowState & DataControlRowState.Insert) != 0) {
1402 if (insertRowStyle != null && !insertRowStyle.IsEmpty)
1403 row.ControlStyle.CopyFrom (insertRowStyle);
1404 else if (editRowStyle != null && !editRowStyle.IsEmpty)
1405 row.ControlStyle.CopyFrom (editRowStyle);
1409 for (int n = 0; n < row.Cells.Count; n++) {
1410 DataControlFieldCell fcell = row.Cells [n] as DataControlFieldCell;
1411 if (fcell != null && fcell.ContainingField != null) {
1412 DataControlField field = fcell.ContainingField;
1413 if (n == 0 && field.ShowHeader) {
1414 if (fieldHeaderStyle != null && !fieldHeaderStyle.IsEmpty)
1415 fcell.ControlStyle.CopyFrom (fieldHeaderStyle);
1416 if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1417 fcell.ControlStyle.CopyFrom (field.HeaderStyle);
1420 if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1421 foreach (Control c in fcell.Controls) {
1422 WebControl wc = c as WebControl;
1424 wc.ControlStyle.MergeWith (field.ControlStyle);
1426 if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1427 fcell.ControlStyle.CopyFrom (field.ItemStyle);
1434 protected internal override void OnInit (EventArgs e)
1436 Page.RegisterRequiresControlState (this);
1440 void OnFieldsChanged (object sender, EventArgs args)
1445 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1447 base.OnDataSourceViewChanged (sender, e);
1451 protected override bool OnBubbleEvent (object source, EventArgs e)
1453 DetailsViewCommandEventArgs args = e as DetailsViewCommandEventArgs;
1455 bool causesValidation = false;
1456 IButtonControl button = args.CommandSource as IButtonControl;
1457 if (button != null && button.CausesValidation) {
1458 Page.Validate (button.ValidationGroup);
1459 causesValidation = true;
1461 ProcessCommand (args, causesValidation);
1464 return base.OnBubbleEvent (source, e);
1467 void ProcessCommand (DetailsViewCommandEventArgs args, bool causesValidation) {
1468 OnItemCommand (args);
1469 ProcessEvent (args.CommandName, args.CommandArgument as string, causesValidation);
1472 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1474 RaisePostBackEvent (eventArgument);
1477 // TODO: This is prolly obsolete
1478 protected virtual void RaisePostBackEvent (string eventArgument)
1480 ValidateEvent (UniqueID, eventArgument);
1481 int i = eventArgument.IndexOf ('$');
1482 CommandEventArgs arg;
1484 arg = new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1486 arg = new CommandEventArgs (eventArgument, null);
1487 ProcessCommand (new DetailsViewCommandEventArgs (this, arg), false);
1490 void ProcessEvent (string eventName, string param, bool causesValidation)
1494 case DataControlCommands.PageCommandName:
1497 case DataControlCommands.FirstPageCommandArgument:
1500 case DataControlCommands.LastPageCommandArgument:
1501 newIndex = PageCount - 1;
1503 case DataControlCommands.NextPageCommandArgument:
1504 newIndex = PageIndex + 1;
1506 case DataControlCommands.PreviousPageCommandArgument:
1507 newIndex = PageIndex - 1;
1511 int.TryParse (param, out paramIndex);
1512 newIndex = paramIndex - 1;
1515 ShowPage (newIndex);
1518 case DataControlCommands.FirstPageCommandArgument:
1522 case DataControlCommands.LastPageCommandArgument:
1523 ShowPage (PageCount - 1);
1526 case DataControlCommands.NextPageCommandArgument:
1527 if (PageIndex < PageCount - 1)
1528 ShowPage (PageIndex + 1);
1531 case DataControlCommands.PreviousPageCommandArgument:
1533 ShowPage (PageIndex - 1);
1536 case DataControlCommands.EditCommandName:
1537 ProcessChangeMode (DetailsViewMode.Edit);
1540 case DataControlCommands.NewCommandName:
1541 ProcessChangeMode (DetailsViewMode.Insert);
1544 case DataControlCommands.UpdateCommandName:
1545 UpdateItem (param, causesValidation);
1548 case DataControlCommands.CancelCommandName:
1552 case DataControlCommands.DeleteCommandName:
1556 case DataControlCommands.InsertCommandName:
1557 InsertItem (causesValidation);
1562 void ShowPage (int newIndex)
1564 DetailsViewPageEventArgs args = new DetailsViewPageEventArgs (newIndex);
1565 OnPageIndexChanging (args);
1567 if (args.Cancel || !IsBoundUsingDataSourceID)
1570 if (args.NewPageIndex < 0 || args.NewPageIndex >= PageCount)
1573 PageIndex = args.NewPageIndex;
1574 OnPageIndexChanged (EventArgs.Empty);
1577 public void ChangeMode (DetailsViewMode newMode)
1579 CurrentMode = newMode;
1583 void ProcessChangeMode (DetailsViewMode newMode)
1585 DetailsViewModeEventArgs args = new DetailsViewModeEventArgs (newMode, false);
1586 OnModeChanging (args);
1588 if (args.Cancel || !IsBoundUsingDataSourceID)
1591 ChangeMode (args.NewMode);
1593 OnModeChanged (EventArgs.Empty);
1598 DetailsViewModeEventArgs args = new DetailsViewModeEventArgs (DetailsViewMode.ReadOnly, true);
1599 OnModeChanging (args);
1601 if (args.Cancel || !IsBoundUsingDataSourceID)
1607 public virtual void UpdateItem (bool causesValidation)
1609 UpdateItem (null, causesValidation);
1612 void UpdateItem (string param, bool causesValidation)
1614 if (causesValidation && Page != null && !Page.IsValid)
1617 if (CurrentMode != DetailsViewMode.Edit) throw new HttpException ();
1619 currentEditOldValues = OldEditValues.Values;
1621 currentEditRowKeys = DataKey.Values;
1622 currentEditNewValues = GetRowValues (false, false);
1624 DetailsViewUpdateEventArgs args = new DetailsViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1625 OnItemUpdating (args);
1627 if (args.Cancel || !IsBoundUsingDataSourceID)
1630 DataSourceView view = GetData ();
1632 throw new HttpException ("The DataSourceView associated to data bound control was null");
1633 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1636 bool UpdateCallback (int recordsAffected, Exception exception)
1638 DetailsViewUpdatedEventArgs dargs = new DetailsViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1639 OnItemUpdated (dargs);
1641 if (!dargs.KeepInEditMode)
1644 return dargs.ExceptionHandled;
1647 public virtual void InsertItem (bool causesValidation)
1649 InsertItem (null, causesValidation);
1652 void InsertItem (string param, bool causesValidation)
1654 if (causesValidation && Page != null && !Page.IsValid)
1657 if (CurrentMode != DetailsViewMode.Insert) throw new HttpException ();
1659 currentEditNewValues = GetRowValues (false, true);
1660 DetailsViewInsertEventArgs args = new DetailsViewInsertEventArgs (param, currentEditNewValues);
1661 OnItemInserting (args);
1663 if (args.Cancel || !IsBoundUsingDataSourceID)
1666 DataSourceView view = GetData ();
1668 throw new HttpException ("The DataSourceView associated to data bound control was null");
1669 view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
1672 bool InsertCallback (int recordsAffected, Exception exception)
1674 DetailsViewInsertedEventArgs dargs = new DetailsViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
1675 OnItemInserted (dargs);
1677 if (!dargs.KeepInInsertMode)
1680 return dargs.ExceptionHandled;
1683 public virtual void DeleteItem ()
1685 currentEditRowKeys = DataKey.Values;
1686 currentEditNewValues = GetRowValues (true, false);
1688 DetailsViewDeleteEventArgs args = new DetailsViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
1689 OnItemDeleting (args);
1691 if (args.Cancel || !IsBoundUsingDataSourceID)
1694 DataSourceView view = GetData ();
1696 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1698 DetailsViewDeletedEventArgs dargs = new DetailsViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1699 OnItemDeleted (dargs);
1701 if (PageIndex > 0 && PageIndex == PageCount - 1)
1706 bool DeleteCallback (int recordsAffected, Exception exception)
1708 DetailsViewDeletedEventArgs dargs = new DetailsViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1709 OnItemDeleted (dargs);
1710 return dargs.ExceptionHandled;
1718 void EndRowEdit (bool switchToDefaultMode) {
1719 if (switchToDefaultMode)
1720 ChangeMode (DefaultMode);
1721 oldEditValues = new DataKey (new OrderedDictionary ());
1722 currentEditRowKeys = null;
1723 currentEditOldValues = null;
1724 currentEditNewValues = null;
1728 protected internal override void LoadControlState (object ob)
1730 if (ob == null) return;
1731 object[] state = (object[]) ob;
1732 base.LoadControlState (state[0]);
1733 pageIndex = (int) state[1];
1734 pageCount = (int) state[2];
1735 CurrentMode = (DetailsViewMode) state[3];
1736 dataKeyNames = (string[]) state[4];
1737 defaultMode = (DetailsViewMode) state[5];
1738 if (state [6] != null)
1739 ((IStateManager) DataKey).LoadViewState (state [6]);
1740 if (state [7] != null)
1741 ((IStateManager) OldEditValues).LoadViewState (state [7]);
1744 protected internal override object SaveControlState ()
1746 object bstate = base.SaveControlState ();
1747 return new object[] {
1754 (key == null ? null : ((IStateManager)key).SaveViewState()),
1755 (oldEditValues == null ? null : ((IStateManager) oldEditValues).SaveViewState ())
1759 protected override void TrackViewState()
1761 base.TrackViewState();
1762 if (columns != null) ((IStateManager)columns).TrackViewState();
1763 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1764 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1765 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1766 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1767 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1768 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1769 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1770 if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
1771 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1772 if (key != null) ((IStateManager)key).TrackViewState();
1773 if (autoFieldProperties != null) {
1774 foreach (IStateManager sm in autoFieldProperties)
1775 sm.TrackViewState ();
1777 if (ControlStyleCreated)
1778 ControlStyle.TrackViewState ();
1781 protected override object SaveViewState()
1783 object[] states = new object [13];
1784 states[0] = base.SaveViewState();
1785 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
1786 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1787 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
1788 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1789 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1790 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1791 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1792 states[8] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
1793 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1794 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1796 if (autoFieldProperties != null) {
1797 object[] data = new object [autoFieldProperties.Length];
1798 bool allNull = true;
1799 for (int n=0; n<data.Length; n++) {
1800 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
1801 if (data [n] != null) allNull = false;
1803 if (!allNull) states [11] = data;
1805 if (ControlStyleCreated)
1806 states [12] = ControlStyle.SaveViewState ();
1808 for (int i = states.Length - 1; i >= 0; i--) {
1809 if (states [i] != null)
1816 protected override void LoadViewState (object savedState)
1818 if (savedState == null) {
1819 base.LoadViewState (null);
1823 object [] states = (object []) savedState;
1825 if (states[11] != null) {
1826 object[] data = (object[]) states [11];
1827 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
1828 for (int n=0; n<data.Length; n++) {
1829 IStateManager p = new AutoGeneratedFieldProperties ();
1830 p.TrackViewState ();
1831 p.LoadViewState (data [n]);
1832 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
1836 base.LoadViewState (states[0]);
1838 if (states[1] != null) ((IStateManager)Fields).LoadViewState (states[1]);
1839 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1840 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
1841 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1842 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1843 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1844 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1845 if (states[8] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[8]);
1846 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1847 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1848 if (states [12] != null)
1849 ControlStyle.LoadViewState (states [12]);
1852 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
1854 RaiseCallbackEvent (eventArgs);
1857 protected virtual void RaiseCallbackEvent (string eventArgs)
1859 string[] clientData = eventArgs.Split ('|');
1860 PageIndex = int.Parse (clientData[0]);
1862 RaisePostBackEvent (clientData[1]);
1866 string ICallbackEventHandler.GetCallbackResult ()
1868 return GetCallbackResult ();
1871 protected virtual string GetCallbackResult ()
1873 PrepareControlHierarchy ();
1875 StringWriter sw = new StringWriter ();
1876 sw.Write (PageIndex.ToString () + '|');
1878 HtmlTextWriter writer = new HtmlTextWriter (sw);
1879 RenderGrid (writer);
1880 return sw.ToString ();
1883 protected virtual string GetCallbackScript (IButtonControl buttonControl, string argument)
1885 if (EnablePagingCallbacks) {
1888 page.ClientScript.RegisterForEventValidation (UniqueID, argument);
1889 return "javascript:DetailsView_ClientEvent (\"" + ClientID + "\",\"" + buttonControl.CommandName + "$" + buttonControl.CommandArgument + "\"); return false;";
1894 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
1896 return GetCallbackScript (control, argument);
1899 protected override void OnPagePreLoad (object sender, EventArgs e)
1901 base.OnPagePreLoad (sender, e);
1903 if (Page.IsPostBack && EnablePagingCallbacks) {
1905 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
1910 const string onPreRenderScript = @"var {0} = new Object ();
1911 {0}.pageIndex = {1};
1916 protected internal override void OnPreRender (EventArgs e)
1918 base.OnPreRender (e);
1920 if (EnablePagingCallbacks)
1922 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(DetailsView), "DetailsView.js")) {
1923 string url = Page.ClientScript.GetWebResourceUrl (typeof(DetailsView), "DetailsView.js");
1924 Page.ClientScript.RegisterClientScriptInclude (typeof(DetailsView), "DetailsView.js", url);
1926 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1928 string cgrid = ClientID + "_data";
1929 string script = String.Format (onPreRenderScript,
1931 ClientScriptManager.GetScriptLiteral (PageIndex),
1932 ClientScriptManager.GetScriptLiteral (UniqueID),
1935 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
1937 // Make sure the basic script infrastructure is rendered
1938 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
1939 Page.ClientScript.GetPostBackClientHyperlink (this, String.Empty, true);
1943 protected internal override void Render (HtmlTextWriter writer)
1945 PrepareControlHierarchy ();
1947 if (EnablePagingCallbacks)
1948 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_div");
1949 writer.RenderBeginTag (HtmlTextWriterTag.Div);
1951 RenderGrid (writer);
1953 writer.RenderEndTag ();
1956 void RenderGrid (HtmlTextWriter writer)
1961 table.Render (writer);
1964 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1966 if (control == null)
1967 throw new ArgumentNullException ("control");
1969 if (control.CausesValidation)
1970 throw new InvalidOperationException ("A button that causes validation in DetailsView '" + ID + "' is attempting to use the container GridView as the post back target. The button should either turn off validation or use itself as the post back container.");
1972 PostBackOptions options = new PostBackOptions (this);
1973 options.Argument = control.CommandName + "$" + control.CommandArgument;
1974 options.RequiresJavaScriptProtocol = true;