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 static readonly object PageIndexChangedEvent = new object();
92 static readonly object PageIndexChangingEvent = new object();
93 static readonly object ItemCommandEvent = new object();
94 static readonly object ItemCreatedEvent = new object();
95 static readonly object ItemDeletedEvent = new object();
96 static readonly object ItemDeletingEvent = new object();
97 static readonly object ItemInsertedEvent = new object();
98 static readonly object ItemInsertingEvent = new object();
99 static readonly object ModeChangingEvent = new object();
100 static readonly object ModeChangedEvent = new object();
101 static readonly object ItemUpdatedEvent = new object();
102 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 PagerSettings pagerSettings = PagerSettings;
902 bool showPager = AllowPaging && pagerSettings.Visible && (dataSource.PageCount > 1);
905 table = CreateTable ();
906 Controls.Add (table);
910 bottomPagerRow = null;
912 // Gets the current data item
915 PageCount = dataSource.DataSourceCount;
916 if (PageIndex >= PageCount && PageCount > 0) {
917 pageIndex = dataSource.CurrentPageIndex = PageCount - 1;
919 if (dataSource.DataSource != null) {
920 IEnumerator e = dataSource.GetEnumerator ();
922 dataItem = e.Current;
927 object lastItem = null;
928 if (dataSource.DataSource != null) {
929 IEnumerator e = dataSource.GetEnumerator ();
930 for (; e.MoveNext (); page++) {
931 lastItem = e.Current;
932 if (page == PageIndex)
933 dataItem = e.Current;
937 if (PageIndex >= PageCount && PageCount > 0) {
938 pageIndex = PageCount - 1;
943 // Main table creation
944 bool emptyRow = PageCount == 0 && CurrentMode != FormViewMode.Insert;
947 headerRow = CreateRow (-1, DataControlRowType.Header, DataControlRowState.Normal);
948 InitializeRow (headerRow);
949 table.Rows.Add (headerRow);
952 if (showPager && pagerSettings.Position == PagerPosition.Top || pagerSettings.Position == PagerPosition.TopAndBottom) {
953 topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
954 InitializePager (topPagerRow, dataSource);
955 table.Rows.Add (topPagerRow);
959 DataControlRowState rstate = GetRowState ();
960 itemRow = CreateRow (0, DataControlRowType.DataRow, rstate);
961 InitializeRow (itemRow);
962 table.Rows.Add (itemRow);
964 switch (CurrentMode) {
965 case FormViewMode.Edit:
966 itemRow = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Edit);
968 case FormViewMode.Insert:
969 itemRow = CreateRow (-1, DataControlRowType.DataRow, DataControlRowState.Insert);
972 itemRow = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
975 InitializeRow (itemRow);
976 table.Rows.Add (itemRow);
980 footerRow = CreateRow (-1, DataControlRowType.Footer, DataControlRowState.Normal);
981 InitializeRow (footerRow);
982 table.Rows.Add (footerRow);
985 if (showPager && pagerSettings.Position == PagerPosition.Bottom || pagerSettings.Position == PagerPosition.TopAndBottom) {
986 bottomPagerRow = CreateRow (0, DataControlRowType.Pager, DataControlRowState.Normal);
987 InitializePager (bottomPagerRow, dataSource);
988 table.Rows.Add (bottomPagerRow);
991 OnItemCreated (EventArgs.Empty);
999 DataControlRowState GetRowState ()
1001 DataControlRowState rstate = DataControlRowState.Normal;
1002 if (CurrentMode == FormViewMode.Edit) rstate |= DataControlRowState.Edit;
1003 else if (CurrentMode == FormViewMode.Insert) rstate |= DataControlRowState.Insert;
1007 protected virtual void InitializePager (FormViewRow row, PagedDataSource dataSource)
1009 TableCell cell = new TableCell ();
1010 cell.ColumnSpan = 2;
1012 if (pagerTemplate != null)
1013 pagerTemplate.InstantiateIn (cell);
1015 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount));
1017 row.Cells.Add (cell);
1020 protected virtual void InitializeRow (FormViewRow row)
1022 TableCell cell = new TableCell ();
1024 if (row.RowType == DataControlRowType.DataRow)
1026 if ((row.RowState & DataControlRowState.Edit) != 0) {
1027 if (editItemTemplate != null)
1028 editItemTemplate.InstantiateIn (cell);
1030 row.Visible = false;
1031 } else if ((row.RowState & DataControlRowState.Insert) != 0) {
1032 if (insertItemTemplate != null)
1033 insertItemTemplate.InstantiateIn (cell);
1035 row.Visible = false;
1037 else if (itemTemplate != null)
1038 itemTemplate.InstantiateIn (cell);
1040 row.Visible = false;
1042 else if (row.RowType == DataControlRowType.EmptyDataRow)
1044 if (emptyDataTemplate != null)
1045 emptyDataTemplate.InstantiateIn (cell);
1046 else if (!String.IsNullOrEmpty (EmptyDataText))
1047 cell.Text = EmptyDataText;
1049 row.Visible = false;
1051 else if (row.RowType == DataControlRowType.Footer)
1053 if (footerTemplate != null)
1054 footerTemplate.InstantiateIn (cell);
1055 else if (!String.IsNullOrEmpty (FooterText))
1056 cell.Text = FooterText;
1058 row.Visible = false;
1060 else if (row.RowType == DataControlRowType.Header)
1062 if (headerTemplate != null)
1063 headerTemplate.InstantiateIn (cell);
1064 else if (!String.IsNullOrEmpty (HeaderText))
1065 cell.Text = HeaderText;
1067 row.Visible = false;
1069 cell.ColumnSpan = 2;
1070 row.Cells.Add (cell);
1073 void FillRowDataKey (object dataItem)
1077 if (cachedKeyProperties == null) {
1078 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
1079 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
1080 for (int n=0; n<DataKeyNames.Length; n++) {
1081 PropertyDescriptor p = props.Find (DataKeyNames [n], true);
1083 throw new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + dataItem.GetType());
1084 cachedKeyProperties [n] = p;
1087 foreach (PropertyDescriptor p in cachedKeyProperties)
1088 KeyTable [p.Name] = p.GetValue (dataItem);
1091 IOrderedDictionary GetRowValues (bool includePrimaryKey)
1093 OrderedDictionary dic = new OrderedDictionary ();
1094 ExtractRowValues (dic, includePrimaryKey);
1098 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, bool includeKeys)
1103 DataControlRowState rowState = Row.RowState;
1104 IBindableTemplate bt;
1106 if ((rowState & DataControlRowState.Insert) != 0)
1107 bt = insertItemTemplate as IBindableTemplate;
1108 else if ((rowState & DataControlRowState.Edit) != 0)
1109 bt = editItemTemplate as IBindableTemplate;
1114 IOrderedDictionary values = bt.ExtractValues (Row.Cells [0]);
1116 foreach (DictionaryEntry e in values) {
1117 if (includeKeys || Array.IndexOf (DataKeyNames, e.Key) == -1)
1118 fieldValues [e.Key] = e.Value;
1123 protected override HtmlTextWriterTag TagKey {
1125 return HtmlTextWriterTag.Table;
1129 public sealed override void DataBind ()
1131 cachedKeyProperties = null;
1134 if (pageCount > 0) {
1135 if (CurrentMode == FormViewMode.Edit)
1136 oldEditValues = new DataKey (GetRowValues (true));
1137 FillRowDataKey (dataItem);
1138 key = new DataKey (KeyTable);
1142 protected internal override void PerformDataBinding (IEnumerable data)
1144 base.PerformDataBinding (data);
1147 protected internal virtual void PrepareControlHierarchy ()
1152 table.Caption = Caption;
1153 table.CaptionAlign = CaptionAlign;
1155 foreach (FormViewRow row in table.Rows) {
1156 switch (row.RowType) {
1157 case DataControlRowType.Header:
1158 if (headerStyle != null && !headerStyle.IsEmpty)
1159 row.ControlStyle.CopyFrom (headerStyle);
1161 case DataControlRowType.Footer:
1162 if (footerStyle != null && !footerStyle.IsEmpty)
1163 row.ControlStyle.CopyFrom (footerStyle);
1165 case DataControlRowType.Pager:
1166 if (pagerStyle != null && !pagerStyle.IsEmpty)
1167 row.ControlStyle.CopyFrom (pagerStyle);
1169 case DataControlRowType.EmptyDataRow:
1170 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1171 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1173 case DataControlRowType.DataRow:
1174 if (rowStyle != null && !rowStyle.IsEmpty)
1175 row.ControlStyle.CopyFrom (rowStyle);
1176 if ((row.RowState & (DataControlRowState.Edit | DataControlRowState.Insert)) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1177 row.ControlStyle.CopyFrom (editRowStyle);
1178 if ((row.RowState & DataControlRowState.Insert) != 0 && insertRowStyle != null && !insertRowStyle.IsEmpty)
1179 row.ControlStyle.CopyFrom (insertRowStyle);
1187 protected internal override void OnInit (EventArgs e)
1189 Page.RegisterRequiresControlState (this);
1193 protected override bool OnBubbleEvent (object source, EventArgs e)
1195 FormViewCommandEventArgs args = e as FormViewCommandEventArgs;
1197 bool causesValidation = false;
1198 IButtonControl button = args.CommandSource as IButtonControl;
1199 if (button != null && button.CausesValidation) {
1200 Page.Validate (button.ValidationGroup);
1201 causesValidation = true;
1203 ProcessCommand (args, causesValidation);
1206 return base.OnBubbleEvent (source, e);
1209 void ProcessCommand (FormViewCommandEventArgs args, bool causesValidation)
1211 OnItemCommand (args);
1212 ProcessEvent (args.CommandName, args.CommandArgument as string, causesValidation);
1215 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1217 RaisePostBackEvent (eventArgument);
1220 protected virtual void RaisePostBackEvent (string eventArgument)
1222 int i = eventArgument.IndexOf ('$');
1223 CommandEventArgs arg;
1225 arg = new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1227 arg = new CommandEventArgs (eventArgument, null);
1228 ProcessCommand (new FormViewCommandEventArgs (this, arg), false);
1231 void ProcessEvent (string eventName, string param, bool causesValidation)
1235 case DataControlCommands.PageCommandName:
1238 case DataControlCommands.FirstPageCommandArgument:
1241 case DataControlCommands.LastPageCommandArgument:
1242 newIndex = PageCount - 1;
1244 case DataControlCommands.NextPageCommandArgument:
1245 newIndex = PageIndex + 1;
1247 case DataControlCommands.PreviousPageCommandArgument:
1248 newIndex = PageIndex - 1;
1252 int.TryParse (param, out paramIndex);
1253 newIndex = paramIndex - 1;
1256 ShowPage (newIndex);
1259 case DataControlCommands.FirstPageCommandArgument:
1263 case DataControlCommands.LastPageCommandArgument:
1264 ShowPage (PageCount - 1);
1267 case DataControlCommands.NextPageCommandArgument:
1268 if (PageIndex < PageCount - 1)
1269 ShowPage (PageIndex + 1);
1272 case DataControlCommands.PreviousPageCommandArgument:
1274 ShowPage (PageIndex - 1);
1277 case DataControlCommands.EditCommandName:
1278 ProcessChangeMode (FormViewMode.Edit, false);
1281 case DataControlCommands.NewCommandName:
1282 ProcessChangeMode (FormViewMode.Insert, false);
1285 case DataControlCommands.UpdateCommandName:
1286 UpdateItem (param, causesValidation);
1289 case DataControlCommands.CancelCommandName:
1293 case DataControlCommands.DeleteCommandName:
1297 case DataControlCommands.InsertCommandName:
1298 InsertItem (causesValidation);
1303 void ShowPage (int index)
1305 FormViewPageEventArgs args = new FormViewPageEventArgs (index);
1306 OnPageIndexChanging (args);
1308 if (args.Cancel || !IsBoundUsingDataSourceID)
1311 int newIndex = args.NewPageIndex;
1312 if (newIndex < 0 || newIndex >= PageCount)
1314 EndRowEdit (false, false);
1315 PageIndex = newIndex;
1316 OnPageIndexChanged (EventArgs.Empty);
1319 public void ChangeMode (FormViewMode newMode)
1321 if (CurrentMode == newMode)
1323 CurrentMode = newMode;
1327 void ProcessChangeMode (FormViewMode newMode, bool cancelingEdit)
1329 FormViewModeEventArgs args = new FormViewModeEventArgs (newMode, cancelingEdit);
1330 OnModeChanging (args);
1332 if (args.Cancel || !IsBoundUsingDataSourceID)
1335 ChangeMode (args.NewMode);
1337 OnModeChanged (EventArgs.Empty);
1342 EndRowEdit (true, true);
1345 public virtual void UpdateItem (bool causesValidation)
1347 UpdateItem (null, causesValidation);
1350 void UpdateItem (string param, bool causesValidation)
1352 if (causesValidation && Page != null && !Page.IsValid)
1355 if (currentMode != FormViewMode.Edit) throw new HttpException ("Must be in Edit mode");
1357 currentEditOldValues = OldEditValues.Values;
1358 currentEditRowKeys = DataKey.Values;
1359 currentEditNewValues = GetRowValues (false);
1361 FormViewUpdateEventArgs args = new FormViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1362 OnItemUpdating (args);
1364 if (args.Cancel || !IsBoundUsingDataSourceID)
1367 DataSourceView view = GetData ();
1369 throw new HttpException ("The DataSourceView associated to data bound control was null");
1370 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1373 bool UpdateCallback (int recordsAffected, Exception exception)
1375 FormViewUpdatedEventArgs dargs = new FormViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1376 OnItemUpdated (dargs);
1378 if (!dargs.KeepInEditMode)
1379 EndRowEdit (true, false);
1381 return dargs.ExceptionHandled;
1384 public virtual void InsertItem (bool causesValidation)
1386 InsertItem (null, causesValidation);
1389 void InsertItem (string param, bool causesValidation)
1391 if (causesValidation && Page != null && !Page.IsValid)
1394 if (currentMode != FormViewMode.Insert) throw new HttpException ("Must be in Insert mode");
1396 currentEditNewValues = GetRowValues (true);
1397 FormViewInsertEventArgs args = new FormViewInsertEventArgs (param, currentEditNewValues);
1398 OnItemInserting (args);
1400 if (args.Cancel || !IsBoundUsingDataSourceID)
1403 DataSourceView view = GetData ();
1405 throw new HttpException ("The DataSourceView associated to data bound control was null");
1406 view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
1409 bool InsertCallback (int recordsAffected, Exception exception)
1411 FormViewInsertedEventArgs dargs = new FormViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
1412 OnItemInserted (dargs);
1414 if (!dargs.KeepInInsertMode)
1415 EndRowEdit (true, false);
1417 return dargs.ExceptionHandled;
1420 public virtual void DeleteItem ()
1422 currentEditRowKeys = DataKey.Values;
1423 currentEditNewValues = GetRowValues (true);
1425 FormViewDeleteEventArgs args = new FormViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
1426 OnItemDeleting (args);
1428 if (args.Cancel || !IsBoundUsingDataSourceID)
1431 if (PageIndex > 0 && PageIndex == PageCount - 1)
1436 DataSourceView view = GetData ();
1438 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1440 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1441 OnItemDeleted (dargs);
1445 bool DeleteCallback (int recordsAffected, Exception exception)
1447 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1448 OnItemDeleted (dargs);
1449 return dargs.ExceptionHandled;
1452 void EndRowEdit (bool switchToDefaultMode, bool cancelingEdit)
1454 if (switchToDefaultMode)
1455 ProcessChangeMode (DefaultMode, cancelingEdit);
1456 oldEditValues = new DataKey (new OrderedDictionary ());
1457 currentEditRowKeys = null;
1458 currentEditOldValues = null;
1459 currentEditNewValues = null;
1463 protected internal override void LoadControlState (object ob)
1465 if (ob == null) return;
1466 object[] state = (object[]) ob;
1467 base.LoadControlState (state[0]);
1468 pageIndex = (int) state[1];
1469 pageCount = (int) state[2];
1470 CurrentMode = (FormViewMode) state[3];
1471 defaultMode = (FormViewMode) state[4];
1472 dataKeyNames = (string[]) state[5];
1473 if (state [6] != null)
1474 ((IStateManager) DataKey).LoadViewState (state [6]);
1475 if (state [7] != null)
1476 ((IStateManager) OldEditValues).LoadViewState (state [7]);
1479 protected internal override object SaveControlState ()
1481 object bstate = base.SaveControlState ();
1482 return new object [] {
1489 (key == null ? null : ((IStateManager)key).SaveViewState()),
1490 (oldEditValues == null ? null : ((IStateManager) oldEditValues).SaveViewState ())
1494 protected override void TrackViewState()
1496 base.TrackViewState();
1497 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1498 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1499 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1500 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1501 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1502 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1503 if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
1504 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1507 protected override object SaveViewState()
1509 object[] states = new object [10];
1510 states[0] = base.SaveViewState();
1511 states[1] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1512 states[2] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1513 states[3] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1514 states[4] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1515 states[5] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1516 states[6] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
1517 states[7] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1518 states[8] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1520 for (int i = states.Length - 1; i >= 0; i--) {
1521 if (states [i] != null)
1528 protected override void LoadViewState (object savedState)
1530 if (savedState == null) {
1531 base.LoadViewState (null);
1535 object [] states = (object []) savedState;
1537 base.LoadViewState (states[0]);
1539 if (states[1] != null) ((IStateManager)PagerSettings).LoadViewState (states[1]);
1540 if (states[2] != null) ((IStateManager)FooterStyle).LoadViewState (states[2]);
1541 if (states[3] != null) ((IStateManager)HeaderStyle).LoadViewState (states[3]);
1542 if (states[4] != null) ((IStateManager)PagerStyle).LoadViewState (states[4]);
1543 if (states[5] != null) ((IStateManager)RowStyle).LoadViewState (states[5]);
1544 if (states[6] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[6]);
1545 if (states[7] != null) ((IStateManager)EditRowStyle).LoadViewState (states[7]);
1546 if (states[8] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[8]);
1549 protected internal override void Render (HtmlTextWriter writer)
1551 PrepareControlHierarchy ();
1556 table.Render (writer);
1559 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1561 if (control == null)
1562 throw new ArgumentNullException ("control");
1564 if (control.CausesValidation)
1565 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.");
1567 PostBackOptions options = new PostBackOptions (this);
1568 options.Argument = control.CommandName + "$" + control.CommandArgument;
1569 options.RequiresJavaScriptProtocol = true;