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 [BrowsableAttribute(false)]
881 public IAutoFieldGenerator RowsGenerator {
886 [WebCategoryAttribute ("Styles")]
887 [PersistenceMode (PersistenceMode.InnerProperty)]
888 [NotifyParentProperty (true)]
889 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
890 [DefaultValue (null)]
891 public TableItemStyle RowStyle {
893 if (rowStyle == null) {
894 rowStyle = new TableItemStyle ();
895 if (IsTrackingViewState)
896 rowStyle.TrackViewState();
902 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
903 [BrowsableAttribute (false)]
904 public object SelectedValue {
905 get { return DataKey.Value; }
908 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
909 [BrowsableAttribute (false)]
910 public virtual DetailsViewRow TopPagerRow {
912 EnsureChildControls ();
917 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
918 [BrowsableAttribute (false)]
919 public virtual object DataItem {
925 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
926 [BrowsableAttribute (false)]
927 public int DataItemCount {
928 get { return PageCount; }
931 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
932 [BrowsableAttribute (false)]
933 public virtual int DataItemIndex {
934 get { return PageIndex; }
937 int IDataItemContainer.DisplayIndex {
938 get { return PageIndex; }
941 int IDataItemContainer.DataItemIndex {
942 get { return DataItemIndex; }
945 public virtual bool IsBindableType (Type type)
947 return type.IsPrimitive || type == typeof (string) || type == typeof (DateTime) || type == typeof (Guid) || type == typeof (Decimal);
950 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
952 DataSourceSelectArguments arg = new DataSourceSelectArguments ();
953 DataSourceView view = GetData ();
954 if (AllowPaging && view.CanPage) {
955 arg.StartRowIndex = PageIndex;
956 if (view.CanRetrieveTotalRowCount) {
957 arg.RetrieveTotalRowCount = true;
961 arg.MaximumRows = -1;
967 protected virtual ICollection CreateFieldSet (object dataItem, bool useDataSource)
969 bool autoGenerate = AutoGenerateRows;
972 IAutoFieldGenerator fieldGenerator = RowsGenerator;
973 if (fieldGenerator != null)
974 return fieldGenerator.GenerateFields (this);
977 ArrayList fields = new ArrayList ();
979 if (AutoGenerateRows) {
981 if (dataItem != null)
982 fields.AddRange (CreateAutoGeneratedRows (dataItem));
984 if (autoFieldProperties != null) {
985 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
986 fields.Add (CreateAutoGeneratedRow (props));
991 fields.AddRange (Fields);
993 if (AutoGenerateEditButton || AutoGenerateDeleteButton || AutoGenerateInsertButton) {
994 CommandField field = new CommandField ();
995 field.ShowEditButton = AutoGenerateEditButton;
996 field.ShowDeleteButton = AutoGenerateDeleteButton;
997 field.ShowInsertButton = AutoGenerateInsertButton;
1004 protected virtual ICollection CreateAutoGeneratedRows (object dataItem)
1006 if (dataItem == null)
1009 ArrayList list = new ArrayList ();
1010 autoFieldProperties = CreateAutoFieldProperties (dataItem);
1011 foreach (AutoGeneratedFieldProperties props in autoFieldProperties)
1012 list.Add (CreateAutoGeneratedRow (props));
1016 protected virtual AutoGeneratedField CreateAutoGeneratedRow (AutoGeneratedFieldProperties fieldProperties)
1018 return new AutoGeneratedField (fieldProperties);
1021 AutoGeneratedFieldProperties[] CreateAutoFieldProperties (object dataItem)
1023 if (IsBindableType (dataItem.GetType ()))
1025 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1026 ((IStateManager) field).TrackViewState ();
1027 field.Name = "Item";
1028 field.DataField = BoundField.ThisExpression;
1029 field.Type = dataItem.GetType ();
1030 return new AutoGeneratedFieldProperties [] { field };
1033 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem, false);
1035 if (props != null && props.Count > 0) {
1036 ArrayList retVal = new ArrayList ();
1037 foreach (PropertyDescriptor current in props) {
1038 if (IsBindableType (current.PropertyType)) {
1039 AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties ();
1040 ((IStateManager) field).TrackViewState ();
1041 field.Name = current.Name;
1042 field.DataField = current.Name;
1043 for (int i = 0; i < DataKeyNames.Length; i++) {
1044 if (string.Compare (DataKeyNames [i], current.Name, StringComparison.InvariantCultureIgnoreCase) == 0) {
1045 field.IsReadOnly = true;
1049 field.Type = current.PropertyType;
1053 if (retVal.Count > 0)
1054 return (AutoGeneratedFieldProperties []) retVal.ToArray (typeof (AutoGeneratedFieldProperties));
1056 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));
1059 protected virtual DetailsViewRow CreateRow (int rowIndex, DataControlRowType rowType, DataControlRowState rowState)
1062 if (rowType == DataControlRowType.Pager)
1063 row = new DetailsViewPagerRow (rowIndex, rowType, rowState);
1065 row = new DetailsViewRow (rowIndex, rowType, rowState);
1069 void RequireBinding ()
1072 RequiresDataBinding = true;
1076 protected virtual Table CreateTable ()
1078 return new ContainedTable (this);
1081 protected override Style CreateControlStyle ()
1083 TableStyle style = new TableStyle ();
1084 style.GridLines = GridLines.Both;
1085 style.CellSpacing = 0;
1089 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
1091 PagedDataSource dataSource = new PagedDataSource ();
1092 dataSource.DataSource = CurrentMode != DetailsViewMode.Insert ? data : null;
1093 dataSource.AllowPaging = AllowPaging;
1094 dataSource.PageSize = 1;
1095 dataSource.CurrentPageIndex = PageIndex;
1097 if (dataBinding && CurrentMode != DetailsViewMode.Insert) {
1098 DataSourceView view = GetData ();
1099 if (view != null && view.CanPage) {
1100 dataSource.AllowServerPaging = true;
1101 if (SelectArguments.RetrieveTotalRowCount)
1102 dataSource.VirtualCount = SelectArguments.TotalRowCount;
1106 bool showPager = AllowPaging && (dataSource.PageCount > 1);
1109 table = CreateTable ();
1110 Controls.Add (table);
1114 bottomPagerRow = null;
1115 ArrayList list = new ArrayList ();
1117 // Gets the current data item
1120 PageCount = dataSource.DataSourceCount;
1121 if (PageIndex >= PageCount && PageCount > 0) {
1122 pageIndex = dataSource.CurrentPageIndex = PageCount - 1;
1124 if (dataSource.DataSource != null) {
1125 IEnumerator e = dataSource.GetEnumerator ();
1127 dataItem = e.Current;
1132 object lastItem = null;
1133 if (dataSource.DataSource != null) {
1134 IEnumerator e = dataSource.GetEnumerator ();
1135 for (; e.MoveNext (); page++) {
1136 lastItem = e.Current;
1137 if (page == PageIndex)
1138 dataItem = e.Current;
1142 if (PageIndex >= PageCount && PageCount > 0) {
1143 pageIndex = PageCount - 1;
1144 dataItem = lastItem;
1148 if (PageCount == 0 && CurrentMode != DetailsViewMode.Insert) {
1149 DetailsViewRow row = CreateEmptyRow ();
1151 table.Rows.Add (row);
1157 // Creates the set of fields to show
1159 ICollection fieldCollection = CreateFieldSet (dataItem, dataBinding && dataItem != null);
1160 DataControlField [] fields = new DataControlField [fieldCollection.Count];
1161 fieldCollection.CopyTo (fields, 0);
1163 foreach (DataControlField field in fields) {
1164 field.Initialize (false, this);
1165 if (EnablePagingCallbacks)
1166 field.ValidateSupportsCallback ();
1169 // Main table creation
1171 headerRow = CreateRow (-1, DataControlRowType.Header, DataControlRowState.Normal);
1172 DataControlFieldCell headerCell = new DataControlFieldCell (null);
1173 headerCell.ColumnSpan = 2;
1174 if (headerTemplate != null)
1175 headerTemplate.InstantiateIn (headerCell);
1176 else if (!String.IsNullOrEmpty (HeaderText))
1177 headerCell.Text = HeaderText;
1179 headerRow.Visible = false;
1180 headerRow.Cells.Add (headerCell);
1181 table.Rows.Add (headerRow);
1183 if (showPager && PagerSettings.Position == PagerPosition.Top ||
1184 PagerSettings.Position == PagerPosition.TopAndBottom) {
1185 topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
1186 InitializePager (topPagerRow, dataSource);
1187 table.Rows.Add (topPagerRow);
1190 foreach (DataControlField field in fields) {
1191 DataControlRowState rstate = GetRowState (list.Count);
1192 DetailsViewRow row = CreateRow (PageIndex, DataControlRowType.DataRow, rstate);
1193 InitializeRow (row, field);
1194 table.Rows.Add (row);
1198 footerRow = CreateRow (-1, DataControlRowType.Footer, DataControlRowState.Normal);
1199 DataControlFieldCell footerCell = new DataControlFieldCell (null);
1200 footerCell.ColumnSpan = 2;
1201 if (footerTemplate != null)
1202 footerTemplate.InstantiateIn (footerCell);
1203 else if (!String.IsNullOrEmpty (FooterText))
1204 footerCell.Text = FooterText;
1206 footerRow.Visible = false;
1207 footerRow.Cells.Add (footerCell);
1208 table.Rows.Add (footerRow);
1210 if (showPager && PagerSettings.Position == PagerPosition.Bottom ||
1211 PagerSettings.Position == PagerPosition.TopAndBottom) {
1212 bottomPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
1213 InitializePager (bottomPagerRow, dataSource);
1214 table.Rows.Add (bottomPagerRow);
1218 rows = new DetailsViewRowCollection (list);
1223 OnItemCreated (EventArgs.Empty);
1228 protected override void EnsureDataBound ()
1230 if (CurrentMode == DetailsViewMode.Insert) {
1231 if (RequiresDataBinding) {
1232 OnDataBinding (EventArgs.Empty);
1233 RequiresDataBinding = false;
1234 InternalPerformDataBinding (null);
1236 OnDataBound (EventArgs.Empty);
1240 base.EnsureDataBound ();
1243 DataControlRowState GetRowState (int index)
1245 DataControlRowState rstate = (index % 2) == 0 ? DataControlRowState.Normal : DataControlRowState.Alternate;
1246 if (CurrentMode == DetailsViewMode.Edit) rstate |= DataControlRowState.Edit;
1247 else if (CurrentMode == DetailsViewMode.Insert) rstate |= DataControlRowState.Insert;
1251 protected virtual void InitializePager (DetailsViewRow row, PagedDataSource dataSource)
1253 TableCell cell = new TableCell ();
1254 cell.ColumnSpan = 2;
1256 if (pagerTemplate != null)
1257 pagerTemplate.InstantiateIn (cell);
1259 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1261 row.Cells.Add (cell);
1264 DetailsViewRow CreateEmptyRow ()
1266 TableCell cell = new TableCell ();
1268 if (emptyDataTemplate != null)
1269 emptyDataTemplate.InstantiateIn (cell);
1270 else if (!String.IsNullOrEmpty (EmptyDataText))
1271 cell.Text = EmptyDataText;
1275 DetailsViewRow row = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
1276 row.Cells.Add (cell);
1280 protected virtual void InitializeRow (DetailsViewRow row, DataControlField field)
1282 if (!field.Visible) {
1283 row.Visible = false;
1287 row.ContainingField = field;
1288 DataControlFieldCell cell;
1290 if (field.ShowHeader) {
1291 cell = new DataControlFieldCell (field);
1292 row.Cells.Add (cell);
1293 field.InitializeCell (cell, DataControlCellType.Header, row.RowState, row.RowIndex);
1296 cell = new DataControlFieldCell (field);
1297 if (!field.ShowHeader)
1298 cell.ColumnSpan = 2;
1299 row.Cells.Add (cell);
1300 field.InitializeCell (cell, DataControlCellType.DataCell, row.RowState, row.RowIndex);
1302 if (CurrentMode == DetailsViewMode.Insert && !field.InsertVisible)
1303 row.Visible = false;
1306 void FillRowDataKey (object dataItem)
1310 if (cachedKeyProperties == null) {
1311 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
1312 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1313 for (int n=0; n<DataKeyNames.Length; n++) {
1314 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1316 throw new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + dataItem.GetType());
1317 cachedKeyProperties [n] = p;
1321 foreach (PropertyDescriptor p in cachedKeyProperties)
1322 KeyTable [p.Name] = p.GetValue (dataItem);
1325 IOrderedDictionary GetRowValues (bool includeReadOnlyFields, bool includePrimaryKey)
1327 OrderedDictionary dic = new OrderedDictionary ();
1328 ExtractRowValues (dic, includeReadOnlyFields, includePrimaryKey);
1332 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, bool includeReadOnlyFields, bool includePrimaryKey)
1334 foreach (DetailsViewRow row in Rows) {
1335 if (row.Cells.Count < 1) continue;
1336 DataControlFieldCell c = row.Cells[row.Cells.Count-1] as DataControlFieldCell;
1338 c.ContainingField.ExtractValuesFromCell (fieldValues, c, row.RowState, includeReadOnlyFields);
1340 if (!includePrimaryKey && DataKeyNames != null)
1341 foreach (string key in DataKeyNames)
1342 fieldValues.Remove (key);
1345 protected override HtmlTextWriterTag TagKey {
1347 if (EnablePagingCallbacks)
1348 return HtmlTextWriterTag.Div;
1350 return HtmlTextWriterTag.Table;
1354 public sealed override void DataBind ()
1356 cachedKeyProperties = null;
1359 if (dataItem != null) {
1360 if (CurrentMode == DetailsViewMode.Edit)
1361 oldEditValues = new DataKey (GetRowValues (false, true));
1362 FillRowDataKey (dataItem);
1363 key = new DataKey (KeyTable);
1367 protected internal override void PerformDataBinding (IEnumerable data)
1369 base.PerformDataBinding (data);
1372 protected internal virtual void PrepareControlHierarchy ()
1377 table.Caption = Caption;
1378 table.CaptionAlign = CaptionAlign;
1380 foreach (DetailsViewRow row in table.Rows) {
1381 switch (row.RowType) {
1382 case DataControlRowType.Header:
1383 if (headerStyle != null && !headerStyle.IsEmpty)
1384 row.ControlStyle.CopyFrom (headerStyle);
1386 case DataControlRowType.Footer:
1387 if (footerStyle != null && !footerStyle.IsEmpty)
1388 row.ControlStyle.CopyFrom (footerStyle);
1390 case DataControlRowType.Pager:
1391 if (pagerStyle != null && !pagerStyle.IsEmpty)
1392 row.ControlStyle.CopyFrom (pagerStyle);
1394 case DataControlRowType.EmptyDataRow:
1395 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1396 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1398 case DataControlRowType.DataRow:
1399 if (rowStyle != null && !rowStyle.IsEmpty)
1400 row.ControlStyle.CopyFrom (rowStyle);
1401 if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
1402 row.ControlStyle.CopyFrom (alternatingRowStyle);
1408 if (row.ContainingField is CommandField) {
1409 if (commandRowStyle != null && !commandRowStyle.IsEmpty)
1410 row.ControlStyle.CopyFrom (commandRowStyle);
1413 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1414 row.ControlStyle.CopyFrom (editRowStyle);
1415 if ((row.RowState & DataControlRowState.Insert) != 0) {
1416 if (insertRowStyle != null && !insertRowStyle.IsEmpty)
1417 row.ControlStyle.CopyFrom (insertRowStyle);
1418 else if (editRowStyle != null && !editRowStyle.IsEmpty)
1419 row.ControlStyle.CopyFrom (editRowStyle);
1423 for (int n = 0; n < row.Cells.Count; n++) {
1424 DataControlFieldCell fcell = row.Cells [n] as DataControlFieldCell;
1425 if (fcell != null && fcell.ContainingField != null) {
1426 DataControlField field = fcell.ContainingField;
1427 if (n == 0 && field.ShowHeader) {
1428 if (fieldHeaderStyle != null && !fieldHeaderStyle.IsEmpty)
1429 fcell.ControlStyle.CopyFrom (fieldHeaderStyle);
1430 if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
1431 fcell.ControlStyle.CopyFrom (field.HeaderStyle);
1434 if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
1435 foreach (Control c in fcell.Controls) {
1436 WebControl wc = c as WebControl;
1438 wc.ControlStyle.MergeWith (field.ControlStyle);
1440 if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
1441 fcell.ControlStyle.CopyFrom (field.ItemStyle);
1448 protected internal override void OnInit (EventArgs e)
1450 Page.RegisterRequiresControlState (this);
1454 void OnFieldsChanged (object sender, EventArgs args)
1459 protected override void OnDataSourceViewChanged (object sender, EventArgs e)
1461 base.OnDataSourceViewChanged (sender, e);
1465 protected override bool OnBubbleEvent (object source, EventArgs e)
1467 DetailsViewCommandEventArgs args = e as DetailsViewCommandEventArgs;
1469 bool causesValidation = false;
1470 IButtonControl button = args.CommandSource as IButtonControl;
1471 if (button != null && button.CausesValidation) {
1472 Page.Validate (button.ValidationGroup);
1473 causesValidation = true;
1475 ProcessCommand (args, causesValidation);
1478 return base.OnBubbleEvent (source, e);
1481 void ProcessCommand (DetailsViewCommandEventArgs args, bool causesValidation) {
1482 OnItemCommand (args);
1483 ProcessEvent (args.CommandName, args.CommandArgument as string, causesValidation);
1486 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1488 RaisePostBackEvent (eventArgument);
1491 // TODO: This is prolly obsolete
1492 protected virtual void RaisePostBackEvent (string eventArgument)
1494 ValidateEvent (UniqueID, eventArgument);
1495 int i = eventArgument.IndexOf ('$');
1496 CommandEventArgs arg;
1498 arg = new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1500 arg = new CommandEventArgs (eventArgument, null);
1501 ProcessCommand (new DetailsViewCommandEventArgs (this, arg), false);
1504 void ProcessEvent (string eventName, string param, bool causesValidation)
1508 case DataControlCommands.PageCommandName:
1511 case DataControlCommands.FirstPageCommandArgument:
1514 case DataControlCommands.LastPageCommandArgument:
1515 newIndex = PageCount - 1;
1517 case DataControlCommands.NextPageCommandArgument:
1518 newIndex = PageIndex + 1;
1520 case DataControlCommands.PreviousPageCommandArgument:
1521 newIndex = PageIndex - 1;
1525 int.TryParse (param, out paramIndex);
1526 newIndex = paramIndex - 1;
1529 ShowPage (newIndex);
1532 case DataControlCommands.FirstPageCommandArgument:
1536 case DataControlCommands.LastPageCommandArgument:
1537 ShowPage (PageCount - 1);
1540 case DataControlCommands.NextPageCommandArgument:
1541 if (PageIndex < PageCount - 1)
1542 ShowPage (PageIndex + 1);
1545 case DataControlCommands.PreviousPageCommandArgument:
1547 ShowPage (PageIndex - 1);
1550 case DataControlCommands.EditCommandName:
1551 ProcessChangeMode (DetailsViewMode.Edit);
1554 case DataControlCommands.NewCommandName:
1555 ProcessChangeMode (DetailsViewMode.Insert);
1558 case DataControlCommands.UpdateCommandName:
1559 UpdateItem (param, causesValidation);
1562 case DataControlCommands.CancelCommandName:
1566 case DataControlCommands.DeleteCommandName:
1570 case DataControlCommands.InsertCommandName:
1571 InsertItem (causesValidation);
1576 void ShowPage (int newIndex)
1578 DetailsViewPageEventArgs args = new DetailsViewPageEventArgs (newIndex);
1579 OnPageIndexChanging (args);
1581 if (args.Cancel || !IsBoundUsingDataSourceID)
1584 if (args.NewPageIndex < 0 || args.NewPageIndex >= PageCount)
1587 PageIndex = args.NewPageIndex;
1588 OnPageIndexChanged (EventArgs.Empty);
1591 public void ChangeMode (DetailsViewMode newMode)
1593 CurrentMode = newMode;
1597 void ProcessChangeMode (DetailsViewMode newMode)
1599 DetailsViewModeEventArgs args = new DetailsViewModeEventArgs (newMode, false);
1600 OnModeChanging (args);
1602 if (args.Cancel || !IsBoundUsingDataSourceID)
1605 ChangeMode (args.NewMode);
1607 OnModeChanged (EventArgs.Empty);
1612 DetailsViewModeEventArgs args = new DetailsViewModeEventArgs (DetailsViewMode.ReadOnly, true);
1613 OnModeChanging (args);
1615 if (args.Cancel || !IsBoundUsingDataSourceID)
1621 public virtual void UpdateItem (bool causesValidation)
1623 UpdateItem (null, causesValidation);
1626 void UpdateItem (string param, bool causesValidation)
1628 if (causesValidation && Page != null && !Page.IsValid)
1631 if (CurrentMode != DetailsViewMode.Edit) throw new HttpException ();
1633 currentEditOldValues = OldEditValues.Values;
1635 currentEditRowKeys = DataKey.Values;
1636 currentEditNewValues = GetRowValues (false, false);
1638 DetailsViewUpdateEventArgs args = new DetailsViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1639 OnItemUpdating (args);
1641 if (args.Cancel || !IsBoundUsingDataSourceID)
1644 DataSourceView view = GetData ();
1646 throw new HttpException ("The DataSourceView associated to data bound control was null");
1647 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1650 bool UpdateCallback (int recordsAffected, Exception exception)
1652 DetailsViewUpdatedEventArgs dargs = new DetailsViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1653 OnItemUpdated (dargs);
1655 if (!dargs.KeepInEditMode)
1658 return dargs.ExceptionHandled;
1661 public virtual void InsertItem (bool causesValidation)
1663 InsertItem (null, causesValidation);
1666 void InsertItem (string param, bool causesValidation)
1668 if (causesValidation && Page != null && !Page.IsValid)
1671 if (CurrentMode != DetailsViewMode.Insert) throw new HttpException ();
1673 currentEditNewValues = GetRowValues (false, true);
1674 DetailsViewInsertEventArgs args = new DetailsViewInsertEventArgs (param, currentEditNewValues);
1675 OnItemInserting (args);
1677 if (args.Cancel || !IsBoundUsingDataSourceID)
1680 DataSourceView view = GetData ();
1682 throw new HttpException ("The DataSourceView associated to data bound control was null");
1683 view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
1686 bool InsertCallback (int recordsAffected, Exception exception)
1688 DetailsViewInsertedEventArgs dargs = new DetailsViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
1689 OnItemInserted (dargs);
1691 if (!dargs.KeepInInsertMode)
1694 return dargs.ExceptionHandled;
1697 public virtual void DeleteItem ()
1699 currentEditRowKeys = DataKey.Values;
1700 currentEditNewValues = GetRowValues (true, false);
1702 DetailsViewDeleteEventArgs args = new DetailsViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
1703 OnItemDeleting (args);
1705 if (args.Cancel || !IsBoundUsingDataSourceID)
1708 DataSourceView view = GetData ();
1710 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1712 DetailsViewDeletedEventArgs dargs = new DetailsViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1713 OnItemDeleted (dargs);
1715 if (PageIndex > 0 && PageIndex == PageCount - 1)
1720 bool DeleteCallback (int recordsAffected, Exception exception)
1722 DetailsViewDeletedEventArgs dargs = new DetailsViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1723 OnItemDeleted (dargs);
1724 return dargs.ExceptionHandled;
1732 void EndRowEdit (bool switchToDefaultMode) {
1733 if (switchToDefaultMode)
1734 ChangeMode (DefaultMode);
1735 oldEditValues = new DataKey (new OrderedDictionary ());
1736 currentEditRowKeys = null;
1737 currentEditOldValues = null;
1738 currentEditNewValues = null;
1742 protected internal override void LoadControlState (object ob)
1744 if (ob == null) return;
1745 object[] state = (object[]) ob;
1746 base.LoadControlState (state[0]);
1747 pageIndex = (int) state[1];
1748 pageCount = (int) state[2];
1749 CurrentMode = (DetailsViewMode) state[3];
1750 dataKeyNames = (string[]) state[4];
1751 defaultMode = (DetailsViewMode) state[5];
1752 if (state [6] != null)
1753 ((IStateManager) DataKey).LoadViewState (state [6]);
1754 if (state [7] != null)
1755 ((IStateManager) OldEditValues).LoadViewState (state [7]);
1758 protected internal override object SaveControlState ()
1760 object bstate = base.SaveControlState ();
1761 return new object[] {
1768 (key == null ? null : ((IStateManager)key).SaveViewState()),
1769 (oldEditValues == null ? null : ((IStateManager) oldEditValues).SaveViewState ())
1773 protected override void TrackViewState()
1775 base.TrackViewState();
1776 if (columns != null) ((IStateManager)columns).TrackViewState();
1777 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1778 if (alternatingRowStyle != null) ((IStateManager)alternatingRowStyle).TrackViewState();
1779 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1780 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1781 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1782 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1783 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1784 if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
1785 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1786 if (key != null) ((IStateManager)key).TrackViewState();
1787 if (autoFieldProperties != null) {
1788 foreach (IStateManager sm in autoFieldProperties)
1789 sm.TrackViewState ();
1791 if (ControlStyleCreated)
1792 ControlStyle.TrackViewState ();
1795 protected override object SaveViewState()
1797 object[] states = new object [13];
1798 states[0] = base.SaveViewState();
1799 states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
1800 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1801 states[3] = (alternatingRowStyle == null ? null : ((IStateManager)alternatingRowStyle).SaveViewState());
1802 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1803 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1804 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1805 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1806 states[8] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
1807 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1808 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1810 if (autoFieldProperties != null) {
1811 object[] data = new object [autoFieldProperties.Length];
1812 bool allNull = true;
1813 for (int n=0; n<data.Length; n++) {
1814 data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
1815 if (data [n] != null) allNull = false;
1817 if (!allNull) states [11] = data;
1819 if (ControlStyleCreated)
1820 states [12] = ControlStyle.SaveViewState ();
1822 for (int i = states.Length - 1; i >= 0; i--) {
1823 if (states [i] != null)
1830 protected override void LoadViewState (object savedState)
1832 if (savedState == null) {
1833 base.LoadViewState (null);
1837 object [] states = (object []) savedState;
1839 if (states[11] != null) {
1840 object[] data = (object[]) states [11];
1841 autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
1842 for (int n=0; n<data.Length; n++) {
1843 IStateManager p = new AutoGeneratedFieldProperties ();
1844 p.TrackViewState ();
1845 p.LoadViewState (data [n]);
1846 autoFieldProperties [n] = (AutoGeneratedFieldProperties) p;
1850 base.LoadViewState (states[0]);
1852 if (states[1] != null) ((IStateManager)Fields).LoadViewState (states[1]);
1853 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1854 if (states[3] != null) ((IStateManager)AlternatingRowStyle).LoadViewState (states[3]);
1855 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1856 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1857 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1858 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1859 if (states[8] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[8]);
1860 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1861 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1862 if (states [12] != null)
1863 ControlStyle.LoadViewState (states [12]);
1866 void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
1868 RaiseCallbackEvent (eventArgs);
1871 protected virtual void RaiseCallbackEvent (string eventArgs)
1873 string[] clientData = eventArgs.Split ('|');
1874 PageIndex = int.Parse (clientData[0]);
1876 RaisePostBackEvent (clientData[1]);
1880 string ICallbackEventHandler.GetCallbackResult ()
1882 return GetCallbackResult ();
1885 protected virtual string GetCallbackResult ()
1887 PrepareControlHierarchy ();
1889 StringWriter sw = new StringWriter ();
1890 sw.Write (PageIndex.ToString () + '|');
1892 HtmlTextWriter writer = new HtmlTextWriter (sw);
1893 RenderGrid (writer);
1894 return sw.ToString ();
1897 protected virtual string GetCallbackScript (IButtonControl buttonControl, string argument)
1899 if (EnablePagingCallbacks) {
1902 page.ClientScript.RegisterForEventValidation (UniqueID, argument);
1903 return "javascript:DetailsView_ClientEvent (\"" + ClientID + "\",\"" + buttonControl.CommandName + "$" + buttonControl.CommandArgument + "\"); return false;";
1908 string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
1910 return GetCallbackScript (control, argument);
1913 protected override void OnPagePreLoad (object sender, EventArgs e)
1915 base.OnPagePreLoad (sender, e);
1917 if (Page.IsPostBack && EnablePagingCallbacks) {
1919 if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
1924 const string onPreRenderScript = @"var {0} = new Object ();
1925 {0}.pageIndex = {1};
1930 protected internal override void OnPreRender (EventArgs e)
1932 base.OnPreRender (e);
1934 if (EnablePagingCallbacks)
1936 if (!Page.ClientScript.IsClientScriptIncludeRegistered (typeof(DetailsView), "DetailsView.js")) {
1937 string url = Page.ClientScript.GetWebResourceUrl (typeof(DetailsView), "DetailsView.js");
1938 Page.ClientScript.RegisterClientScriptInclude (typeof(DetailsView), "DetailsView.js", url);
1940 Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
1942 string cgrid = ClientID + "_data";
1943 string script = String.Format (onPreRenderScript,
1945 ClientScriptManager.GetScriptLiteral (PageIndex),
1946 ClientScriptManager.GetScriptLiteral (UniqueID),
1949 Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
1951 // Make sure the basic script infrastructure is rendered
1952 Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
1953 Page.ClientScript.GetPostBackClientHyperlink (this, String.Empty, true);
1957 protected internal override void Render (HtmlTextWriter writer)
1959 PrepareControlHierarchy ();
1961 if (EnablePagingCallbacks)
1962 writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_div");
1963 writer.RenderBeginTag (HtmlTextWriterTag.Div);
1965 RenderGrid (writer);
1967 writer.RenderEndTag ();
1970 void RenderGrid (HtmlTextWriter writer)
1975 table.Render (writer);
1978 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1980 if (control == null)
1981 throw new ArgumentNullException ("control");
1983 if (control.CausesValidation)
1984 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.");
1986 PostBackOptions options = new PostBackOptions (this);
1987 options.Argument = control.CommandName + "$" + control.CommandArgument;
1988 options.RequiresJavaScriptProtocol = true;