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; RequireBinding (); }
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; RequireBinding (); }
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; RequireBinding (); }
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; RequireBinding (); }
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; RequireBinding (); }
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; RequireBinding (); }
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; RequireBinding (); }
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 PerformDataBinding (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);
993 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]);
1114 foreach (DictionaryEntry e in values) {
1115 if (includeKeys || Array.IndexOf (DataKeyNames, e.Key) == -1)
1116 fieldValues [e.Key] = e.Value;
1121 protected override HtmlTextWriterTag TagKey {
1123 return HtmlTextWriterTag.Table;
1127 public sealed override void DataBind ()
1129 cachedKeyProperties = null;
1132 if (pageCount > 0) {
1133 if (CurrentMode == FormViewMode.Edit)
1134 oldEditValues = new DataKey (GetRowValues (true));
1135 FillRowDataKey (dataItem);
1136 key = new DataKey (KeyTable);
1140 protected internal override void PerformDataBinding (IEnumerable data)
1142 base.PerformDataBinding (data);
1145 protected internal virtual void PrepareControlHierarchy ()
1150 table.Caption = Caption;
1151 table.CaptionAlign = CaptionAlign;
1153 foreach (FormViewRow row in table.Rows) {
1154 switch (row.RowType) {
1155 case DataControlRowType.Header:
1156 if (headerStyle != null && !headerStyle.IsEmpty)
1157 row.ControlStyle.CopyFrom (headerStyle);
1159 case DataControlRowType.Footer:
1160 if (footerStyle != null && !footerStyle.IsEmpty)
1161 row.ControlStyle.CopyFrom (footerStyle);
1163 case DataControlRowType.Pager:
1164 if (pagerStyle != null && !pagerStyle.IsEmpty)
1165 row.ControlStyle.CopyFrom (pagerStyle);
1167 case DataControlRowType.EmptyDataRow:
1168 if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
1169 row.ControlStyle.CopyFrom (emptyDataRowStyle);
1171 case DataControlRowType.DataRow:
1172 if (rowStyle != null && !rowStyle.IsEmpty)
1173 row.ControlStyle.CopyFrom (rowStyle);
1174 if ((row.RowState & (DataControlRowState.Edit | DataControlRowState.Insert)) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
1175 row.ControlStyle.CopyFrom (editRowStyle);
1176 if ((row.RowState & DataControlRowState.Insert) != 0 && insertRowStyle != null && !insertRowStyle.IsEmpty)
1177 row.ControlStyle.CopyFrom (insertRowStyle);
1185 protected internal override void OnInit (EventArgs e)
1187 Page.RegisterRequiresControlState (this);
1191 protected override bool OnBubbleEvent (object source, EventArgs e)
1193 FormViewCommandEventArgs args = e as FormViewCommandEventArgs;
1195 bool causesValidation = false;
1196 IButtonControl button = args.CommandSource as IButtonControl;
1197 if (button != null && button.CausesValidation) {
1198 Page.Validate (button.ValidationGroup);
1199 causesValidation = true;
1201 ProcessCommand (args, causesValidation);
1204 return base.OnBubbleEvent (source, e);
1207 void ProcessCommand (FormViewCommandEventArgs args, bool causesValidation)
1209 OnItemCommand (args);
1210 ProcessEvent (args.CommandName, args.CommandArgument as string, causesValidation);
1213 void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
1215 RaisePostBackEvent (eventArgument);
1218 protected virtual void RaisePostBackEvent (string eventArgument)
1220 int i = eventArgument.IndexOf ('$');
1221 CommandEventArgs arg;
1223 arg = new CommandEventArgs (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1225 arg = new CommandEventArgs (eventArgument, null);
1226 ProcessCommand (new FormViewCommandEventArgs (this, arg), false);
1229 void ProcessEvent (string eventName, string param, bool causesValidation)
1233 case DataControlCommands.PageCommandName:
1236 case DataControlCommands.FirstPageCommandArgument:
1239 case DataControlCommands.LastPageCommandArgument:
1240 newIndex = PageCount - 1;
1242 case DataControlCommands.NextPageCommandArgument:
1243 newIndex = PageIndex + 1;
1245 case DataControlCommands.PreviousPageCommandArgument:
1246 newIndex = PageIndex - 1;
1250 int.TryParse (param, out paramIndex);
1251 newIndex = paramIndex - 1;
1254 ShowPage (newIndex);
1257 case DataControlCommands.FirstPageCommandArgument:
1261 case DataControlCommands.LastPageCommandArgument:
1262 ShowPage (PageCount - 1);
1265 case DataControlCommands.NextPageCommandArgument:
1266 if (PageIndex < PageCount - 1)
1267 ShowPage (PageIndex + 1);
1270 case DataControlCommands.PreviousPageCommandArgument:
1272 ShowPage (PageIndex - 1);
1275 case DataControlCommands.EditCommandName:
1276 ProcessChangeMode (FormViewMode.Edit, false);
1279 case DataControlCommands.NewCommandName:
1280 ProcessChangeMode (FormViewMode.Insert, false);
1283 case DataControlCommands.UpdateCommandName:
1284 UpdateItem (param, causesValidation);
1287 case DataControlCommands.CancelCommandName:
1291 case DataControlCommands.DeleteCommandName:
1295 case DataControlCommands.InsertCommandName:
1296 InsertItem (causesValidation);
1301 void ShowPage (int index)
1303 FormViewPageEventArgs args = new FormViewPageEventArgs (index);
1304 OnPageIndexChanging (args);
1306 if (args.Cancel || !IsBoundUsingDataSourceID)
1309 int newIndex = args.NewPageIndex;
1310 if (newIndex < 0 || newIndex >= PageCount)
1312 EndRowEdit (false, false);
1313 PageIndex = newIndex;
1314 OnPageIndexChanged (EventArgs.Empty);
1317 public void ChangeMode (FormViewMode newMode)
1319 if (CurrentMode == newMode)
1321 CurrentMode = newMode;
1325 void ProcessChangeMode (FormViewMode newMode, bool cancelingEdit)
1327 FormViewModeEventArgs args = new FormViewModeEventArgs (newMode, cancelingEdit);
1328 OnModeChanging (args);
1330 if (args.Cancel || !IsBoundUsingDataSourceID)
1333 ChangeMode (args.NewMode);
1335 OnModeChanged (EventArgs.Empty);
1340 EndRowEdit (true, true);
1343 public virtual void UpdateItem (bool causesValidation)
1345 UpdateItem (null, causesValidation);
1348 void UpdateItem (string param, bool causesValidation)
1350 if (causesValidation && Page != null && !Page.IsValid)
1353 if (currentMode != FormViewMode.Edit) throw new HttpException ("Must be in Edit mode");
1355 currentEditOldValues = OldEditValues.Values;
1356 currentEditRowKeys = DataKey.Values;
1357 currentEditNewValues = GetRowValues (false);
1359 FormViewUpdateEventArgs args = new FormViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1360 OnItemUpdating (args);
1362 if (args.Cancel || !IsBoundUsingDataSourceID)
1365 DataSourceView view = GetData ();
1367 throw new HttpException ("The DataSourceView associated to data bound control was null");
1368 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1371 bool UpdateCallback (int recordsAffected, Exception exception)
1373 FormViewUpdatedEventArgs dargs = new FormViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1374 OnItemUpdated (dargs);
1376 if (!dargs.KeepInEditMode)
1377 EndRowEdit (true, false);
1379 return dargs.ExceptionHandled;
1382 public virtual void InsertItem (bool causesValidation)
1384 InsertItem (null, causesValidation);
1387 void InsertItem (string param, bool causesValidation)
1389 if (causesValidation && Page != null && !Page.IsValid)
1392 if (currentMode != FormViewMode.Insert) throw new HttpException ("Must be in Insert mode");
1394 currentEditNewValues = GetRowValues (true);
1395 FormViewInsertEventArgs args = new FormViewInsertEventArgs (param, currentEditNewValues);
1396 OnItemInserting (args);
1398 if (args.Cancel || !IsBoundUsingDataSourceID)
1401 DataSourceView view = GetData ();
1403 throw new HttpException ("The DataSourceView associated to data bound control was null");
1404 view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
1407 bool InsertCallback (int recordsAffected, Exception exception)
1409 FormViewInsertedEventArgs dargs = new FormViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
1410 OnItemInserted (dargs);
1412 if (!dargs.KeepInInsertMode)
1413 EndRowEdit (true, false);
1415 return dargs.ExceptionHandled;
1418 public virtual void DeleteItem ()
1420 currentEditRowKeys = DataKey.Values;
1421 currentEditNewValues = GetRowValues (true);
1423 FormViewDeleteEventArgs args = new FormViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
1424 OnItemDeleting (args);
1426 if (args.Cancel || !IsBoundUsingDataSourceID)
1429 if (PageIndex > 0 && PageIndex == PageCount - 1)
1434 DataSourceView view = GetData ();
1436 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1438 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1439 OnItemDeleted (dargs);
1443 bool DeleteCallback (int recordsAffected, Exception exception)
1445 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1446 OnItemDeleted (dargs);
1447 return dargs.ExceptionHandled;
1450 void EndRowEdit (bool switchToDefaultMode, bool cancelingEdit)
1452 if (switchToDefaultMode)
1453 ProcessChangeMode (DefaultMode, cancelingEdit);
1454 oldEditValues = new DataKey (new OrderedDictionary ());
1455 currentEditRowKeys = null;
1456 currentEditOldValues = null;
1457 currentEditNewValues = null;
1461 protected internal override void LoadControlState (object ob)
1463 if (ob == null) return;
1464 object[] state = (object[]) ob;
1465 base.LoadControlState (state[0]);
1466 pageIndex = (int) state[1];
1467 pageCount = (int) state[2];
1468 CurrentMode = (FormViewMode) state[3];
1469 defaultMode = (FormViewMode) state[4];
1470 dataKeyNames = (string[]) state[5];
1471 if (state [6] != null)
1472 ((IStateManager) DataKey).LoadViewState (state [6]);
1473 if (state [7] != null)
1474 ((IStateManager) OldEditValues).LoadViewState (state [7]);
1477 protected internal override object SaveControlState ()
1479 object bstate = base.SaveControlState ();
1480 return new object [] {
1487 (key == null ? null : ((IStateManager)key).SaveViewState()),
1488 (oldEditValues == null ? null : ((IStateManager) oldEditValues).SaveViewState ())
1492 protected override void TrackViewState()
1494 base.TrackViewState();
1495 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1496 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1497 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1498 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1499 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1500 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1501 if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
1502 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1505 protected override object SaveViewState()
1507 object[] states = new object [10];
1508 states[0] = base.SaveViewState();
1509 states[1] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1510 states[2] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1511 states[3] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1512 states[4] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1513 states[5] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1514 states[6] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
1515 states[7] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1516 states[8] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1518 for (int i = states.Length - 1; i >= 0; i--) {
1519 if (states [i] != null)
1526 protected override void LoadViewState (object savedState)
1528 if (savedState == null) {
1529 base.LoadViewState (null);
1533 object [] states = (object []) savedState;
1535 base.LoadViewState (states[0]);
1537 if (states[1] != null) ((IStateManager)PagerSettings).LoadViewState (states[1]);
1538 if (states[2] != null) ((IStateManager)FooterStyle).LoadViewState (states[2]);
1539 if (states[3] != null) ((IStateManager)HeaderStyle).LoadViewState (states[3]);
1540 if (states[4] != null) ((IStateManager)PagerStyle).LoadViewState (states[4]);
1541 if (states[5] != null) ((IStateManager)RowStyle).LoadViewState (states[5]);
1542 if (states[6] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[6]);
1543 if (states[7] != null) ((IStateManager)EditRowStyle).LoadViewState (states[7]);
1544 if (states[8] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[8]);
1547 protected internal override void Render (HtmlTextWriter writer)
1549 PrepareControlHierarchy ();
1554 table.Render (writer);
1557 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1559 if (control == null)
1560 throw new ArgumentNullException ("control");
1562 if (control.CausesValidation)
1563 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.");
1565 PostBackOptions options = new PostBackOptions (this);
1566 options.Argument = control.CommandName + "$" + control.CommandArgument;
1567 options.RequiresJavaScriptProtocol = true;