2 // System.Web.UI.WebControls.FormView.cs
5 // Lluis Sanchez Gual (lluis@novell.com)
7 // (C) 2005 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.ComponentModel;
36 using System.Security.Permissions;
39 using System.Reflection;
41 namespace System.Web.UI.WebControls
43 [SupportsEventValidation]
44 [DesignerAttribute ("System.Web.UI.Design.WebControls.FormViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
45 [ControlValuePropertyAttribute ("SelectedValue")]
46 [DefaultEventAttribute ("PageIndexChanging")]
47 [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48 [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
49 public class FormView: CompositeDataBoundControl, IDataItemContainer, INamingContainer, IPostBackEventHandler, IPostBackContainer
54 FormViewRow headerRow;
55 FormViewRow footerRow;
56 FormViewRow bottomPagerRow;
57 FormViewRow topPagerRow;
60 IOrderedDictionary currentEditRowKeys;
61 IOrderedDictionary currentEditNewValues;
62 IOrderedDictionary currentEditOldValues;
64 ITemplate pagerTemplate;
65 ITemplate emptyDataTemplate;
66 ITemplate headerTemplate;
67 ITemplate footerTemplate;
68 ITemplate editItemTemplate;
69 ITemplate insertItemTemplate;
70 ITemplate itemTemplate;
72 PropertyDescriptor[] cachedKeyProperties;
73 readonly string[] emptyKeys = new string[0];
74 readonly string unhandledEventExceptionMessage = "The FormView '{0}' fired event {1} which wasn't handled.";
77 PagerSettings pagerSettings;
79 TableItemStyle editRowStyle;
80 TableItemStyle insertRowStyle;
81 TableItemStyle emptyDataRowStyle;
82 TableItemStyle footerStyle;
83 TableItemStyle headerStyle;
84 TableItemStyle pagerStyle;
85 TableItemStyle rowStyle;
87 IOrderedDictionary _keyTable;
89 DataKey oldEditValues;
91 private static readonly object PageIndexChangedEvent = new object();
92 private static readonly object PageIndexChangingEvent = new object();
93 private static readonly object ItemCommandEvent = new object();
94 private static readonly object ItemCreatedEvent = new object();
95 private static readonly object ItemDeletedEvent = new object();
96 private static readonly object ItemDeletingEvent = new object();
97 private static readonly object ItemInsertedEvent = new object();
98 private static readonly object ItemInsertingEvent = new object();
99 private static readonly object ModeChangingEvent = new object();
100 private static readonly object ModeChangedEvent = new object();
101 private static readonly object ItemUpdatedEvent = new object();
102 private static readonly object ItemUpdatingEvent = new object();
106 FormViewMode currentMode = FormViewMode.ReadOnly;
110 public event EventHandler PageIndexChanged {
111 add { Events.AddHandler (PageIndexChangedEvent, value); }
112 remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
115 public event FormViewPageEventHandler PageIndexChanging {
116 add { Events.AddHandler (PageIndexChangingEvent, value); }
117 remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
120 public event FormViewCommandEventHandler ItemCommand {
121 add { Events.AddHandler (ItemCommandEvent, value); }
122 remove { Events.RemoveHandler (ItemCommandEvent, value); }
125 public event EventHandler ItemCreated {
126 add { Events.AddHandler (ItemCreatedEvent, value); }
127 remove { Events.RemoveHandler (ItemCreatedEvent, value); }
130 public event FormViewDeletedEventHandler ItemDeleted {
131 add { Events.AddHandler (ItemDeletedEvent, value); }
132 remove { Events.RemoveHandler (ItemDeletedEvent, value); }
135 public event FormViewDeleteEventHandler ItemDeleting {
136 add { Events.AddHandler (ItemDeletingEvent, value); }
137 remove { Events.RemoveHandler (ItemDeletingEvent, value); }
140 public event FormViewInsertedEventHandler ItemInserted {
141 add { Events.AddHandler (ItemInsertedEvent, value); }
142 remove { Events.RemoveHandler (ItemInsertedEvent, value); }
145 public event FormViewInsertEventHandler ItemInserting {
146 add { Events.AddHandler (ItemInsertingEvent, value); }
147 remove { Events.RemoveHandler (ItemInsertingEvent, value); }
150 public event FormViewModeEventHandler ModeChanging {
151 add { Events.AddHandler (ModeChangingEvent, value); }
152 remove { Events.RemoveHandler (ModeChangingEvent, value); }
155 public event EventHandler ModeChanged {
156 add { Events.AddHandler (ModeChangedEvent, value); }
157 remove { Events.RemoveHandler (ModeChangedEvent, value); }
160 public event FormViewUpdatedEventHandler ItemUpdated {
161 add { Events.AddHandler (ItemUpdatedEvent, value); }
162 remove { Events.RemoveHandler (ItemUpdatedEvent, value); }
165 public event FormViewUpdateEventHandler ItemUpdating {
166 add { Events.AddHandler (ItemUpdatingEvent, value); }
167 remove { Events.RemoveHandler (ItemUpdatingEvent, value); }
170 protected virtual void OnPageIndexChanged (EventArgs e)
172 if (Events != null) {
173 EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
174 if (eh != null) eh (this, e);
178 protected virtual void OnPageIndexChanging (FormViewPageEventArgs e)
180 if (Events != null) {
181 FormViewPageEventHandler eh = (FormViewPageEventHandler) Events [PageIndexChangingEvent];
187 if (!IsBoundUsingDataSourceID)
188 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "PageIndexChanging"));
191 protected virtual void OnItemCommand (FormViewCommandEventArgs e)
193 if (Events != null) {
194 FormViewCommandEventHandler eh = (FormViewCommandEventHandler) Events [ItemCommandEvent];
195 if (eh != null) eh (this, e);
199 protected virtual void OnItemCreated (EventArgs e)
201 if (Events != null) {
202 EventHandler eh = (EventHandler) Events [ItemCreatedEvent];
203 if (eh != null) eh (this, e);
207 protected virtual void OnItemDeleted (FormViewDeletedEventArgs e)
209 if (Events != null) {
210 FormViewDeletedEventHandler eh = (FormViewDeletedEventHandler) Events [ItemDeletedEvent];
211 if (eh != null) eh (this, e);
215 protected virtual void OnItemInserted (FormViewInsertedEventArgs e)
217 if (Events != null) {
218 FormViewInsertedEventHandler eh = (FormViewInsertedEventHandler) Events [ItemInsertedEvent];
219 if (eh != null) eh (this, e);
223 protected virtual void OnItemInserting (FormViewInsertEventArgs e)
225 if (Events != null) {
226 FormViewInsertEventHandler eh = (FormViewInsertEventHandler) Events [ItemInsertingEvent];
232 if (!IsBoundUsingDataSourceID)
233 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ItemInserting"));
236 protected virtual void OnItemDeleting (FormViewDeleteEventArgs e)
238 if (Events != null) {
239 FormViewDeleteEventHandler eh = (FormViewDeleteEventHandler) Events [ItemDeletingEvent];
245 if (!IsBoundUsingDataSourceID)
246 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ItemDeleting"));
249 protected virtual void OnModeChanged (EventArgs e)
251 if (Events != null) {
252 EventHandler eh = (EventHandler) Events [ModeChangedEvent];
253 if (eh != null) eh (this, e);
257 protected virtual void OnModeChanging (FormViewModeEventArgs e)
259 if (Events != null) {
260 FormViewModeEventHandler eh = (FormViewModeEventHandler) Events [ModeChangingEvent];
266 if (!IsBoundUsingDataSourceID)
267 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ModeChanging"));
270 protected virtual void OnItemUpdated (FormViewUpdatedEventArgs e)
272 if (Events != null) {
273 FormViewUpdatedEventHandler eh = (FormViewUpdatedEventHandler) Events [ItemUpdatedEvent];
274 if (eh != null) eh (this, e);
278 protected virtual void OnItemUpdating (FormViewUpdateEventArgs e)
280 if (Events != null) {
281 FormViewUpdateEventHandler eh = (FormViewUpdateEventHandler) Events [ItemUpdatingEvent];
287 if (!IsBoundUsingDataSourceID)
288 throw new HttpException (String.Format (unhandledEventExceptionMessage, ID, "ItemUpdating"));
292 [WebCategoryAttribute ("Paging")]
293 [DefaultValueAttribute (false)]
294 public virtual bool AllowPaging {
296 object ob = ViewState ["AllowPaging"];
297 if (ob != null) return (bool) ob;
301 ViewState ["AllowPaging"] = value;
306 [UrlPropertyAttribute]
307 [WebCategoryAttribute ("Appearance")]
308 [DefaultValueAttribute ("")]
309 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
310 public virtual string BackImageUrl {
312 if (ControlStyleCreated)
313 return ((TableStyle) ControlStyle).BackImageUrl;
317 ((TableStyle) ControlStyle).BackImageUrl = value;
321 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
322 [BrowsableAttribute (false)]
323 public virtual FormViewRow BottomPagerRow {
325 EnsureChildControls ();
326 return bottomPagerRow;
330 [WebCategoryAttribute ("Accessibility")]
331 [DefaultValueAttribute ("")]
332 [LocalizableAttribute (true)]
333 public virtual string Caption {
335 object ob = ViewState ["Caption"];
336 if (ob != null) return (string) ob;
340 ViewState ["Caption"] = value;
345 [WebCategoryAttribute ("Accessibility")]
346 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
347 public virtual TableCaptionAlign CaptionAlign
350 object o = ViewState ["CaptionAlign"];
351 if(o != null) return (TableCaptionAlign) o;
352 return TableCaptionAlign.NotSet;
355 ViewState ["CaptionAlign"] = value;
360 [WebCategoryAttribute ("Layout")]
361 [DefaultValueAttribute (-1)]
362 public virtual int CellPadding
365 if (ControlStyleCreated)
366 return ((TableStyle) ControlStyle).CellPadding;
370 ((TableStyle) ControlStyle).CellPadding = value;
374 [WebCategoryAttribute ("Layout")]
375 [DefaultValueAttribute (0)]
376 public virtual int CellSpacing
379 if (ControlStyleCreated)
380 return ((TableStyle) ControlStyle).CellSpacing;
384 ((TableStyle) ControlStyle).CellSpacing = value;
388 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
389 [BrowsableAttribute (false)]
390 public FormViewMode CurrentMode {
392 return hasCurrentMode ? currentMode : DefaultMode;
395 hasCurrentMode = true;
400 FormViewMode defaultMode;
402 [DefaultValueAttribute (FormViewMode.ReadOnly)]
403 [WebCategoryAttribute ("Behavior")]
404 public virtual FormViewMode DefaultMode {
414 string[] dataKeyNames;
415 [DefaultValueAttribute (null)]
416 [WebCategoryAttribute ("Data")]
417 [TypeConverter (typeof(StringArrayConverter))]
418 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
419 public virtual string[] DataKeyNames
422 if (dataKeyNames == null)
427 dataKeyNames = value;
432 IOrderedDictionary KeyTable {
434 if (_keyTable == null) {
435 _keyTable = new OrderedDictionary (DataKeyNames.Length);
441 [BrowsableAttribute (false)]
442 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
443 public virtual DataKey DataKey {
446 key= new DataKey (KeyTable);
452 DataKey OldEditValues {
454 if (oldEditValues == null) {
455 oldEditValues = new DataKey (new OrderedDictionary ());
457 return oldEditValues;
461 [DefaultValue (null)]
462 [TemplateContainer (typeof(FormView), BindingDirection.TwoWay)]
463 [PersistenceMode (PersistenceMode.InnerProperty)]
465 public virtual ITemplate EditItemTemplate {
466 get { return editItemTemplate; }
467 set { editItemTemplate = value; }
470 [WebCategoryAttribute ("Styles")]
471 [PersistenceMode (PersistenceMode.InnerProperty)]
472 [NotifyParentProperty (true)]
473 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
474 [DefaultValueAttribute (null)]
475 public TableItemStyle EditRowStyle {
477 if (editRowStyle == null) {
478 editRowStyle = new TableItemStyle ();
479 if (IsTrackingViewState)
480 editRowStyle.TrackViewState();
486 [WebCategoryAttribute ("Styles")]
487 [PersistenceMode (PersistenceMode.InnerProperty)]
488 [NotifyParentProperty (true)]
489 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
490 [DefaultValueAttribute (null)]
491 public TableItemStyle EmptyDataRowStyle {
493 if (emptyDataRowStyle == null) {
494 emptyDataRowStyle = new TableItemStyle ();
495 if (IsTrackingViewState)
496 emptyDataRowStyle.TrackViewState();
498 return emptyDataRowStyle;
502 [DefaultValue (null)]
503 [TemplateContainer (typeof(FormView), BindingDirection.OneWay)]
504 [PersistenceMode (PersistenceMode.InnerProperty)]
506 public virtual ITemplate EmptyDataTemplate {
507 get { return emptyDataTemplate; }
508 set { emptyDataTemplate = value; }
511 [LocalizableAttribute (true)]
512 [WebCategoryAttribute ("Appearance")]
513 [DefaultValueAttribute ("")]
514 public virtual string EmptyDataText {
516 object ob = ViewState ["EmptyDataText"];
517 if (ob != null) return (string) ob;
521 ViewState ["EmptyDataText"] = value;
526 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
527 [BrowsableAttribute (false)]
528 public virtual FormViewRow FooterRow {
530 EnsureChildControls ();
535 [DefaultValue (null)]
536 [TemplateContainer (typeof(FormView), BindingDirection.OneWay)]
537 [PersistenceMode (PersistenceMode.InnerProperty)]
539 public virtual ITemplate FooterTemplate {
540 get { return footerTemplate; }
541 set { footerTemplate = value; }
544 [LocalizableAttribute (true)]
545 [WebCategoryAttribute ("Appearance")]
546 [DefaultValueAttribute ("")]
547 public virtual string FooterText {
549 object ob = ViewState ["FooterText"];
550 if (ob != null) return (string) ob;
554 ViewState ["FooterText"] = value;
559 [WebCategoryAttribute ("Styles")]
560 [PersistenceMode (PersistenceMode.InnerProperty)]
561 [NotifyParentProperty (true)]
562 [DefaultValue (null)]
563 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
564 public TableItemStyle FooterStyle {
566 if (footerStyle == null) {
567 footerStyle = new TableItemStyle ();
568 if (IsTrackingViewState)
569 footerStyle.TrackViewState();
575 [WebCategoryAttribute ("Appearance")]
576 [DefaultValueAttribute (GridLines.None)]
577 public virtual GridLines GridLines {
579 if (ControlStyleCreated)
580 return ((TableStyle) ControlStyle).GridLines;
581 return GridLines.None;
584 ((TableStyle) ControlStyle).GridLines = value;
588 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
589 [BrowsableAttribute (false)]
590 public virtual FormViewRow HeaderRow {
592 EnsureChildControls ();
597 [WebCategoryAttribute ("Styles")]
598 [PersistenceMode (PersistenceMode.InnerProperty)]
599 [NotifyParentProperty (true)]
600 [DefaultValue (null)]
601 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
602 public TableItemStyle HeaderStyle {
604 if (headerStyle == null) {
605 headerStyle = new TableItemStyle ();
606 if (IsTrackingViewState)
607 headerStyle.TrackViewState();
613 [DefaultValue (null)]
614 [TemplateContainer (typeof(FormView), BindingDirection.OneWay)]
615 [PersistenceMode (PersistenceMode.InnerProperty)]
617 public virtual ITemplate HeaderTemplate {
618 get { return headerTemplate; }
619 set { headerTemplate = value; }
622 [LocalizableAttribute (true)]
623 [WebCategoryAttribute ("Appearance")]
624 [DefaultValueAttribute ("")]
625 public virtual string HeaderText {
627 object ob = ViewState ["HeaderText"];
628 if (ob != null) return (string) ob;
632 ViewState ["HeaderText"] = value;
637 [Category ("Layout")]
638 [DefaultValueAttribute (HorizontalAlign.NotSet)]
639 public virtual HorizontalAlign HorizontalAlign {
641 if (ControlStyleCreated)
642 return ((TableStyle) ControlStyle).HorizontalAlign;
643 return HorizontalAlign.NotSet;
646 ((TableStyle) ControlStyle).HorizontalAlign = value;
650 [DefaultValue (null)]
651 [TemplateContainer (typeof(FormView), BindingDirection.TwoWay)]
652 [PersistenceMode (PersistenceMode.InnerProperty)]
654 public virtual ITemplate InsertItemTemplate {
655 get { return insertItemTemplate; }
656 set { insertItemTemplate = value; }
659 [WebCategoryAttribute ("Styles")]
660 [PersistenceMode (PersistenceMode.InnerProperty)]
661 [NotifyParentProperty (true)]
662 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
663 [DefaultValueAttribute (null)]
664 public TableItemStyle InsertRowStyle {
666 if (insertRowStyle == null) {
667 insertRowStyle = new TableItemStyle ();
668 if (IsTrackingViewState)
669 insertRowStyle.TrackViewState();
671 return insertRowStyle;
675 [DefaultValue (null)]
676 [TemplateContainer (typeof(FormView), BindingDirection.TwoWay)]
677 [PersistenceMode (PersistenceMode.InnerProperty)]
679 public virtual ITemplate ItemTemplate {
680 get { return itemTemplate; }
681 set { itemTemplate = value; }
684 [BrowsableAttribute (false)]
685 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
686 public virtual int PageCount {
695 [WebCategoryAttribute ("Paging")]
696 [BindableAttribute (true, BindingDirection.OneWay)]
697 [DefaultValueAttribute (0)]
698 public virtual int PageIndex {
704 throw new ArgumentOutOfRangeException ("PageIndex must be non-negative");
705 if (pageIndex == value || value == -1)
712 [WebCategoryAttribute ("Paging")]
713 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
714 [NotifyParentPropertyAttribute (true)]
715 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
716 public virtual PagerSettings PagerSettings {
718 if (pagerSettings == null) {
719 pagerSettings = new PagerSettings (this);
720 if (IsTrackingViewState)
721 ((IStateManager)pagerSettings).TrackViewState ();
723 return pagerSettings;
727 [WebCategoryAttribute ("Styles")]
728 [PersistenceMode (PersistenceMode.InnerProperty)]
729 [NotifyParentProperty (true)]
730 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
731 public TableItemStyle PagerStyle {
733 if (pagerStyle == null) {
734 pagerStyle = new TableItemStyle ();
735 if (IsTrackingViewState)
736 pagerStyle.TrackViewState();
743 [DefaultValue (null)]
744 [TemplateContainerAttribute (typeof (FormView))]
745 [PersistenceMode (PersistenceMode.InnerProperty)]
747 public virtual ITemplate PagerTemplate {
748 get { return pagerTemplate; }
749 set { pagerTemplate = value; }
752 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
753 [BrowsableAttribute (false)]
754 public virtual FormViewRow Row {
756 EnsureChildControls ();
761 [WebCategoryAttribute ("Styles")]
762 [PersistenceMode (PersistenceMode.InnerProperty)]
763 [NotifyParentProperty (true)]
764 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
765 [DefaultValue (null)]
766 public TableItemStyle RowStyle {
768 if (rowStyle == null) {
769 rowStyle = new TableItemStyle ();
770 if (IsTrackingViewState)
771 rowStyle.TrackViewState();
777 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
778 [BrowsableAttribute (false)]
779 public object SelectedValue {
780 get { return DataKey.Value; }
783 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
784 [BrowsableAttribute (false)]
785 public virtual FormViewRow TopPagerRow {
787 EnsureChildControls ();
792 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
793 [BrowsableAttribute (false)]
794 public virtual object DataItem {
800 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
801 [BrowsableAttribute (false)]
802 public int DataItemCount {
803 get { return PageCount; }
806 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
807 [BrowsableAttribute (false)]
808 public virtual int DataItemIndex {
809 get { return PageIndex; }
812 int IDataItemContainer.DataItemIndex {
813 get { return DataItemIndex; }
816 int IDataItemContainer.DisplayIndex {
817 get { return PageIndex; }
820 public virtual bool IsBindableType (Type type)
822 return type.IsPrimitive || type == typeof (string) || type == typeof (DateTime) || type == typeof (Guid) || type == typeof (Decimal);
825 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
827 DataSourceSelectArguments arg = new DataSourceSelectArguments ();
828 DataSourceView view = GetData ();
829 if (AllowPaging && view.CanPage) {
830 arg.StartRowIndex = PageIndex;
831 if (view.CanRetrieveTotalRowCount) {
832 arg.RetrieveTotalRowCount = true;
836 arg.MaximumRows = -1;
842 protected virtual FormViewRow CreateRow (int rowIndex, DataControlRowType rowType, DataControlRowState rowState)
844 if (rowType == DataControlRowType.Pager)
845 return new FormViewPagerRow (rowIndex, rowType, rowState);
847 return new FormViewRow (rowIndex, rowType, rowState);
850 void RequireBinding ()
853 RequiresDataBinding = true;
857 protected virtual Table CreateTable ()
859 return new ContainedTable (this);
862 protected override void EnsureDataBound ()
864 if (CurrentMode == FormViewMode.Insert) {
865 if (RequiresDataBinding) {
866 OnDataBinding (EventArgs.Empty);
867 RequiresDataBinding = false;
868 InternalPerformDataBinding (null);
870 OnDataBound (EventArgs.Empty);
874 base.EnsureDataBound ();
877 protected override Style CreateControlStyle ()
879 TableStyle style = new TableStyle (ViewState);
880 style.CellSpacing = 0;
884 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
886 PagedDataSource dataSource = new PagedDataSource ();
887 dataSource.DataSource = CurrentMode != FormViewMode.Insert ? data : null;
888 dataSource.AllowPaging = AllowPaging;
889 dataSource.PageSize = 1;
890 dataSource.CurrentPageIndex = PageIndex;
892 if (dataBinding && CurrentMode != FormViewMode.Insert) {
893 DataSourceView view = GetData ();
894 if (view != null && view.CanPage) {
895 dataSource.AllowServerPaging = true;
896 if (SelectArguments.RetrieveTotalRowCount)
897 dataSource.VirtualCount = SelectArguments.TotalRowCount;
901 bool showPager = AllowPaging && (dataSource.PageCount > 1);
904 table = CreateTable ();
905 Controls.Add (table);
909 bottomPagerRow = null;
911 // Gets the current data item
914 PageCount = dataSource.DataSourceCount;
915 if (PageIndex >= PageCount && PageCount > 0) {
916 pageIndex = dataSource.CurrentPageIndex = PageCount - 1;
918 if (dataSource.DataSource != null) {
919 IEnumerator e = dataSource.GetEnumerator ();
921 dataItem = e.Current;
926 object lastItem = null;
927 if (dataSource.DataSource != null) {
928 IEnumerator e = dataSource.GetEnumerator ();
929 for (; e.MoveNext (); page++) {
930 lastItem = e.Current;
931 if (page == PageIndex)
932 dataItem = e.Current;
936 if (PageIndex >= PageCount && PageCount > 0) {
937 pageIndex = PageCount - 1;
942 // Main table creation
943 bool emptyRow = PageCount == 0 && CurrentMode != FormViewMode.Insert;
946 headerRow = CreateRow (-1, DataControlRowType.Header, DataControlRowState.Normal);
947 InitializeRow (headerRow);
948 table.Rows.Add (headerRow);
951 if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
952 topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
953 InitializePager (topPagerRow, dataSource);
954 table.Rows.Add (topPagerRow);
958 DataControlRowState rstate = GetRowState ();
959 itemRow = CreateRow (0, DataControlRowType.DataRow, rstate);
960 InitializeRow (itemRow);
961 table.Rows.Add (itemRow);
963 switch (CurrentMode) {
964 case FormViewMode.Edit:
965 itemRow = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Edit);
967 case FormViewMode.Insert:
968 itemRow = CreateRow (-1, DataControlRowType.DataRow, DataControlRowState.Insert);
971 itemRow = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
974 InitializeRow (itemRow);
975 table.Rows.Add (itemRow);
979 footerRow = CreateRow (-1, DataControlRowType.Footer, DataControlRowState.Normal);
980 InitializeRow (footerRow);
981 table.Rows.Add (footerRow);
984 if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
985 bottomPagerRow = CreateRow (0, DataControlRowType.Pager, DataControlRowState.Normal);
986 InitializePager (bottomPagerRow, dataSource);
987 table.Rows.Add (bottomPagerRow);
990 OnItemCreated (EventArgs.Empty);
998 DataControlRowState GetRowState ()
1000 DataControlRowState rstate = DataControlRowState.Normal;
1001 if (CurrentMode == FormViewMode.Edit) rstate |= DataControlRowState.Edit;
1002 else if (CurrentMode == FormViewMode.Insert) rstate |= DataControlRowState.Insert;
1006 protected virtual void InitializePager (FormViewRow row, PagedDataSource dataSource)
1008 TableCell cell = new TableCell ();
1009 cell.ColumnSpan = 2;
1011 if (pagerTemplate != null)
1012 pagerTemplate.InstantiateIn (cell);
1014 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1016 row.Cells.Add (cell);
1019 protected virtual void InitializeRow (FormViewRow row)
1021 TableCell cell = new TableCell ();
1023 if (row.RowType == DataControlRowType.DataRow)
1025 if ((row.RowState & DataControlRowState.Edit) != 0) {
1026 if (editItemTemplate != null)
1027 editItemTemplate.InstantiateIn (cell);
1029 row.Visible = false;
1030 } else if ((row.RowState & DataControlRowState.Insert) != 0) {
1031 if (insertItemTemplate != null)
1032 insertItemTemplate.InstantiateIn (cell);
1034 row.Visible = false;
1036 else if (itemTemplate != null)
1037 itemTemplate.InstantiateIn (cell);
1039 row.Visible = false;
1041 else if (row.RowType == DataControlRowType.EmptyDataRow)
1043 if (emptyDataTemplate != null)
1044 emptyDataTemplate.InstantiateIn (cell);
1045 else if (!String.IsNullOrEmpty (EmptyDataText))
1046 cell.Text = EmptyDataText;
1048 row.Visible = false;
1050 else if (row.RowType == DataControlRowType.Footer)
1052 if (footerTemplate != null)
1053 footerTemplate.InstantiateIn (cell);
1054 else if (!String.IsNullOrEmpty (FooterText))
1055 cell.Text = FooterText;
1057 row.Visible = false;
1059 else if (row.RowType == DataControlRowType.Header)
1061 if (headerTemplate != null)
1062 headerTemplate.InstantiateIn (cell);
1063 else if (!String.IsNullOrEmpty (HeaderText))
1064 cell.Text = HeaderText;
1066 row.Visible = false;
1068 cell.ColumnSpan = 2;
1069 row.Cells.Add (cell);
1072 void FillRowDataKey (object dataItem)
1076 if (cachedKeyProperties == null) {
1077 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
1078 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1079 for (int n=0; n<DataKeyNames.Length; n++) {
1080 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1082 throw new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + dataItem.GetType());
1083 cachedKeyProperties [n] = p;
1086 foreach (PropertyDescriptor p in cachedKeyProperties)
1087 KeyTable [p.Name] = p.GetValue (dataItem);
1090 IOrderedDictionary GetRowValues (bool includePrimaryKey)
1092 OrderedDictionary dic = new OrderedDictionary ();
1093 ExtractRowValues (dic, includePrimaryKey);
1097 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, bool includeKeys)
1102 DataControlRowState rowState = Row.RowState;
1103 IBindableTemplate bt;
1105 if ((rowState & DataControlRowState.Insert) != 0)
1106 bt = insertItemTemplate as IBindableTemplate;
1107 else if ((rowState & DataControlRowState.Edit) != 0)
1108 bt = editItemTemplate as IBindableTemplate;
1113 IOrderedDictionary values = bt.ExtractValues (Row.Cells [0]);
1115 foreach (DictionaryEntry e in values) {
1116 if (includeKeys || Array.IndexOf (DataKeyNames, e.Key) == -1)
1117 fieldValues [e.Key] = e.Value;
1122 protected override HtmlTextWriterTag TagKey {
1124 return HtmlTextWriterTag.Table;
1128 public sealed override void DataBind ()
1130 cachedKeyProperties = null;
1133 if (pageCount > 0) {
1134 if (CurrentMode == FormViewMode.Edit)
1135 oldEditValues = new DataKey (GetRowValues (true));
1136 FillRowDataKey (dataItem);
1137 key = new DataKey (KeyTable);
1141 protected internal override void PerformDataBinding (IEnumerable data)
1143 base.PerformDataBinding (data);
1146 protected internal virtual void PrepareControlHierarchy ()
1151 table.Caption = Caption;
1152 table.CaptionAlign = CaptionAlign;
1154 foreach (FormViewRow row in table.Rows) {
1155 switch (row.RowType) {
1156 case DataControlRowType.Header:
1157 if (headerStyle != null && !headerStyle.IsEmpty)
1158 row.ControlStyle.CopyFrom (headerStyle);
1160 case DataControlRowType.Footer:
1161 if (footerStyle != null && !footerStyle.IsEmpty)
1162 row.ControlStyle.CopyFrom (footerStyle);
1164 case DataControlRowType.Pager:
1165 if (pagerStyle != null && !pagerStyle.IsEmpty)
1166 row.ControlStyle.CopyFrom (pagerStyle);
1168 case DataControlRowType.EmptyDataRow:
1169 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1170 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1172 case DataControlRowType.DataRow:
1173 if (rowStyle != null && !rowStyle.IsEmpty)
1174 row.ControlStyle.CopyFrom (rowStyle);
1175 if ((row.RowState & (DataControlRowState.Edit | DataControlRowState.Insert)) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1176 row.ControlStyle.CopyFrom (editRowStyle);
1177 if ((row.RowState & DataControlRowState.Insert) != 0 && insertRowStyle != null && !insertRowStyle.IsEmpty)
1178 row.ControlStyle.CopyFrom (insertRowStyle);
1186 protected internal override void OnInit (EventArgs e)
1188 Page.RegisterRequiresControlState (this);
1192 protected override bool OnBubbleEvent (object source, EventArgs e)
1194 FormViewCommandEventArgs args = e as FormViewCommandEventArgs;
1196 bool causesValidation = false;
1197 IButtonControl button = args.CommandSource as IButtonControl;
1198 if (button != null && button.CausesValidation) {
1199 Page.Validate (button.ValidationGroup);
1200 causesValidation = true;
1202 ProcessCommand (args, causesValidation);
1205 return base.OnBubbleEvent (source, e);
1208 void ProcessCommand (FormViewCommandEventArgs args, bool causesValidation)
1210 OnItemCommand (args);
1211 ProcessEvent (args.CommandName, args.CommandArgument as string, causesValidation);
1214 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1216 RaisePostBackEvent (eventArgument);
1219 protected virtual void RaisePostBackEvent (string eventArgument)
1221 int i = eventArgument.IndexOf ('$');
1222 CommandEventArgs arg;
1224 arg = new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1226 arg = new CommandEventArgs (eventArgument, null);
1227 ProcessCommand (new FormViewCommandEventArgs (this, arg), false);
1230 void ProcessEvent (string eventName, string param, bool causesValidation)
1234 case DataControlCommands.PageCommandName:
1237 case DataControlCommands.FirstPageCommandArgument:
1240 case DataControlCommands.LastPageCommandArgument:
1241 newIndex = PageCount - 1;
1243 case DataControlCommands.NextPageCommandArgument:
1244 newIndex = PageIndex + 1;
1246 case DataControlCommands.PreviousPageCommandArgument:
1247 newIndex = PageIndex - 1;
1251 int.TryParse (param, out paramIndex);
1252 newIndex = paramIndex - 1;
1255 ShowPage (newIndex);
1258 case DataControlCommands.FirstPageCommandArgument:
1262 case DataControlCommands.LastPageCommandArgument:
1263 ShowPage (PageCount - 1);
1266 case DataControlCommands.NextPageCommandArgument:
1267 if (PageIndex < PageCount - 1)
1268 ShowPage (PageIndex + 1);
1271 case DataControlCommands.PreviousPageCommandArgument:
1273 ShowPage (PageIndex - 1);
1276 case DataControlCommands.EditCommandName:
1277 ProcessChangeMode (FormViewMode.Edit, false);
1280 case DataControlCommands.NewCommandName:
1281 ProcessChangeMode (FormViewMode.Insert, false);
1284 case DataControlCommands.UpdateCommandName:
1285 UpdateItem (param, causesValidation);
1288 case DataControlCommands.CancelCommandName:
1292 case DataControlCommands.DeleteCommandName:
1296 case DataControlCommands.InsertCommandName:
1297 InsertItem (causesValidation);
1302 void ShowPage (int index)
1304 FormViewPageEventArgs args = new FormViewPageEventArgs (index);
1305 OnPageIndexChanging (args);
1307 if (args.Cancel || !IsBoundUsingDataSourceID)
1310 int newIndex = args.NewPageIndex;
1311 if (newIndex < 0 || newIndex >= PageCount)
1313 EndRowEdit (false, false);
1314 PageIndex = newIndex;
1315 OnPageIndexChanged (EventArgs.Empty);
1318 public void ChangeMode (FormViewMode newMode)
1320 if (CurrentMode == newMode)
1322 CurrentMode = newMode;
1326 void ProcessChangeMode (FormViewMode newMode, bool cancelingEdit)
1328 FormViewModeEventArgs args = new FormViewModeEventArgs (newMode, cancelingEdit);
1329 OnModeChanging (args);
1331 if (args.Cancel || !IsBoundUsingDataSourceID)
1334 ChangeMode (args.NewMode);
1336 OnModeChanged (EventArgs.Empty);
1341 EndRowEdit (true, true);
1344 public virtual void UpdateItem (bool causesValidation)
1346 UpdateItem (null, causesValidation);
1349 void UpdateItem (string param, bool causesValidation)
1351 if (causesValidation && Page != null && !Page.IsValid)
1354 if (currentMode != FormViewMode.Edit) throw new HttpException ("Must be in Edit mode");
1356 currentEditOldValues = OldEditValues.Values;
1357 currentEditRowKeys = DataKey.Values;
1358 currentEditNewValues = GetRowValues (false);
1360 FormViewUpdateEventArgs args = new FormViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1361 OnItemUpdating (args);
1363 if (args.Cancel || !IsBoundUsingDataSourceID)
1366 DataSourceView view = GetData ();
1368 throw new HttpException ("The DataSourceView associated to data bound control was null");
1369 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1372 bool UpdateCallback (int recordsAffected, Exception exception)
1374 FormViewUpdatedEventArgs dargs = new FormViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1375 OnItemUpdated (dargs);
1377 if (!dargs.KeepInEditMode)
1378 EndRowEdit (true, false);
1380 return dargs.ExceptionHandled;
1383 public virtual void InsertItem (bool causesValidation)
1385 InsertItem (null, causesValidation);
1388 void InsertItem (string param, bool causesValidation)
1390 if (causesValidation && Page != null && !Page.IsValid)
1393 if (currentMode != FormViewMode.Insert) throw new HttpException ("Must be in Insert mode");
1395 currentEditNewValues = GetRowValues (true);
1396 FormViewInsertEventArgs args = new FormViewInsertEventArgs (param, currentEditNewValues);
1397 OnItemInserting (args);
1399 if (args.Cancel || !IsBoundUsingDataSourceID)
1402 DataSourceView view = GetData ();
1404 throw new HttpException ("The DataSourceView associated to data bound control was null");
1405 view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
1408 bool InsertCallback (int recordsAffected, Exception exception)
1410 FormViewInsertedEventArgs dargs = new FormViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
1411 OnItemInserted (dargs);
1413 if (!dargs.KeepInInsertMode)
1414 EndRowEdit (true, false);
1416 return dargs.ExceptionHandled;
1419 public virtual void DeleteItem ()
1421 currentEditRowKeys = DataKey.Values;
1422 currentEditNewValues = GetRowValues (true);
1424 FormViewDeleteEventArgs args = new FormViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
1425 OnItemDeleting (args);
1427 if (args.Cancel || !IsBoundUsingDataSourceID)
1430 if (PageIndex > 0 && PageIndex == PageCount - 1)
1435 DataSourceView view = GetData ();
1437 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1439 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1440 OnItemDeleted (dargs);
1444 bool DeleteCallback (int recordsAffected, Exception exception)
1446 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1447 OnItemDeleted (dargs);
1448 return dargs.ExceptionHandled;
1451 void EndRowEdit (bool switchToDefaultMode, bool cancelingEdit)
1453 if (switchToDefaultMode)
1454 ProcessChangeMode (DefaultMode, cancelingEdit);
1455 oldEditValues = new DataKey (new OrderedDictionary ());
1456 currentEditRowKeys = null;
1457 currentEditOldValues = null;
1458 currentEditNewValues = null;
1462 protected internal override void LoadControlState (object ob)
1464 if (ob == null) return;
1465 object[] state = (object[]) ob;
1466 base.LoadControlState (state[0]);
1467 pageIndex = (int) state[1];
1468 pageCount = (int) state[2];
1469 CurrentMode = (FormViewMode) state[3];
1470 defaultMode = (FormViewMode) state[4];
1471 dataKeyNames = (string[]) state[5];
1472 if (state [6] != null)
1473 ((IStateManager) DataKey).LoadViewState (state [6]);
1474 if (state [7] != null)
1475 ((IStateManager) OldEditValues).LoadViewState (state [7]);
1478 protected internal override object SaveControlState ()
1480 object bstate = base.SaveControlState ();
1481 return new object [] {
1488 (key == null ? null : ((IStateManager)key).SaveViewState()),
1489 (oldEditValues == null ? null : ((IStateManager) oldEditValues).SaveViewState ())
1493 protected override void TrackViewState()
1495 base.TrackViewState();
1496 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1497 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1498 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1499 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1500 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1501 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1502 if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
1503 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1506 protected override object SaveViewState()
1508 object[] states = new object [10];
1509 states[0] = base.SaveViewState();
1510 states[1] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1511 states[2] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1512 states[3] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1513 states[4] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1514 states[5] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1515 states[6] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
1516 states[7] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1517 states[8] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1519 for (int i = states.Length - 1; i >= 0; i--) {
1520 if (states [i] != null)
1527 protected override void LoadViewState (object savedState)
1529 if (savedState == null) {
1530 base.LoadViewState (null);
1534 object [] states = (object []) savedState;
1536 base.LoadViewState (states[0]);
1538 if (states[1] != null) ((IStateManager)PagerSettings).LoadViewState (states[1]);
1539 if (states[2] != null) ((IStateManager)FooterStyle).LoadViewState (states[2]);
1540 if (states[3] != null) ((IStateManager)HeaderStyle).LoadViewState (states[3]);
1541 if (states[4] != null) ((IStateManager)PagerStyle).LoadViewState (states[4]);
1542 if (states[5] != null) ((IStateManager)RowStyle).LoadViewState (states[5]);
1543 if (states[6] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[6]);
1544 if (states[7] != null) ((IStateManager)EditRowStyle).LoadViewState (states[7]);
1545 if (states[8] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[8]);
1548 protected internal override void Render (HtmlTextWriter writer)
1550 PrepareControlHierarchy ();
1555 table.Render (writer);
1558 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1560 if (control == null)
1561 throw new ArgumentNullException ("control");
1563 if (control.CausesValidation)
1564 throw new InvalidOperationException ("A button that causes validation in FormView '" + 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.");
1566 PostBackOptions options = new PostBackOptions (this);
1567 options.Argument = control.CommandName + "$" + control.CommandArgument;
1568 options.RequiresJavaScriptProtocol = true;