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];
76 PagerSettings pagerSettings;
78 TableItemStyle editRowStyle;
79 TableItemStyle insertRowStyle;
80 TableItemStyle emptyDataRowStyle;
81 TableItemStyle footerStyle;
82 TableItemStyle headerStyle;
83 TableItemStyle pagerStyle;
84 TableItemStyle rowStyle;
87 DataKey oldEditValues;
89 private static readonly object PageIndexChangedEvent = new object();
90 private static readonly object PageIndexChangingEvent = new object();
91 private static readonly object ItemCommandEvent = new object();
92 private static readonly object ItemCreatedEvent = new object();
93 private static readonly object ItemDeletedEvent = new object();
94 private static readonly object ItemDeletingEvent = new object();
95 private static readonly object ItemInsertedEvent = new object();
96 private static readonly object ItemInsertingEvent = new object();
97 private static readonly object ModeChangingEvent = new object();
98 private static readonly object ModeChangedEvent = new object();
99 private static readonly object ItemUpdatedEvent = new object();
100 private static readonly object ItemUpdatingEvent = new object();
104 FormViewMode currentMode = FormViewMode.ReadOnly;
109 key = new DataKey (new OrderedDictionary ());
112 public event EventHandler PageIndexChanged {
113 add { Events.AddHandler (PageIndexChangedEvent, value); }
114 remove { Events.RemoveHandler (PageIndexChangedEvent, value); }
117 public event FormViewPageEventHandler PageIndexChanging {
118 add { Events.AddHandler (PageIndexChangingEvent, value); }
119 remove { Events.RemoveHandler (PageIndexChangingEvent, value); }
122 public event FormViewCommandEventHandler ItemCommand {
123 add { Events.AddHandler (ItemCommandEvent, value); }
124 remove { Events.RemoveHandler (ItemCommandEvent, value); }
127 public event EventHandler ItemCreated {
128 add { Events.AddHandler (ItemCreatedEvent, value); }
129 remove { Events.RemoveHandler (ItemCreatedEvent, value); }
132 public event FormViewDeletedEventHandler ItemDeleted {
133 add { Events.AddHandler (ItemDeletedEvent, value); }
134 remove { Events.RemoveHandler (ItemDeletedEvent, value); }
137 public event FormViewDeleteEventHandler ItemDeleting {
138 add { Events.AddHandler (ItemDeletingEvent, value); }
139 remove { Events.RemoveHandler (ItemDeletingEvent, value); }
142 public event FormViewInsertedEventHandler ItemInserted {
143 add { Events.AddHandler (ItemInsertedEvent, value); }
144 remove { Events.RemoveHandler (ItemInsertedEvent, value); }
147 public event FormViewInsertEventHandler ItemInserting {
148 add { Events.AddHandler (ItemInsertingEvent, value); }
149 remove { Events.RemoveHandler (ItemInsertingEvent, value); }
152 public event FormViewModeEventHandler ModeChanging {
153 add { Events.AddHandler (ModeChangingEvent, value); }
154 remove { Events.RemoveHandler (ModeChangingEvent, value); }
157 public event EventHandler ModeChanged {
158 add { Events.AddHandler (ModeChangedEvent, value); }
159 remove { Events.RemoveHandler (ModeChangedEvent, value); }
162 public event FormViewUpdatedEventHandler ItemUpdated {
163 add { Events.AddHandler (ItemUpdatedEvent, value); }
164 remove { Events.RemoveHandler (ItemUpdatedEvent, value); }
167 public event FormViewUpdateEventHandler ItemUpdating {
168 add { Events.AddHandler (ItemUpdatingEvent, value); }
169 remove { Events.RemoveHandler (ItemUpdatingEvent, value); }
172 protected virtual void OnPageIndexChanged (EventArgs e)
174 if (Events != null) {
175 EventHandler eh = (EventHandler) Events [PageIndexChangedEvent];
176 if (eh != null) eh (this, e);
180 protected virtual void OnPageIndexChanging (FormViewPageEventArgs e)
182 if (Events != null) {
183 FormViewPageEventHandler eh = (FormViewPageEventHandler) Events [PageIndexChangingEvent];
184 if (eh != null) eh (this, e);
188 protected virtual void OnItemCommand (FormViewCommandEventArgs e)
190 if (Events != null) {
191 FormViewCommandEventHandler eh = (FormViewCommandEventHandler) Events [ItemCommandEvent];
192 if (eh != null) eh (this, e);
196 protected virtual void OnItemCreated (EventArgs e)
198 if (Events != null) {
199 EventHandler eh = (EventHandler) Events [ItemCreatedEvent];
200 if (eh != null) eh (this, e);
204 protected virtual void OnItemDeleted (FormViewDeletedEventArgs e)
206 if (Events != null) {
207 FormViewDeletedEventHandler eh = (FormViewDeletedEventHandler) Events [ItemDeletedEvent];
208 if (eh != null) eh (this, e);
212 protected virtual void OnItemInserted (FormViewInsertedEventArgs e)
214 if (Events != null) {
215 FormViewInsertedEventHandler eh = (FormViewInsertedEventHandler) Events [ItemInsertedEvent];
216 if (eh != null) eh (this, e);
220 protected virtual void OnItemInserting (FormViewInsertEventArgs e)
222 if (Events != null) {
223 FormViewInsertEventHandler eh = (FormViewInsertEventHandler) Events [ItemInsertingEvent];
224 if (eh != null) eh (this, e);
228 protected virtual void OnItemDeleting (FormViewDeleteEventArgs e)
230 if (Events != null) {
231 FormViewDeleteEventHandler eh = (FormViewDeleteEventHandler) Events [ItemDeletingEvent];
232 if (eh != null) eh (this, e);
236 protected virtual void OnModeChanged (EventArgs e)
238 if (Events != null) {
239 EventHandler eh = (EventHandler) Events [ModeChangedEvent];
240 if (eh != null) eh (this, e);
244 protected virtual void OnModeChanging (FormViewModeEventArgs e)
246 if (Events != null) {
247 FormViewModeEventHandler eh = (FormViewModeEventHandler) Events [ModeChangingEvent];
248 if (eh != null) eh (this, e);
252 protected virtual void OnItemUpdated (FormViewUpdatedEventArgs e)
254 if (Events != null) {
255 FormViewUpdatedEventHandler eh = (FormViewUpdatedEventHandler) Events [ItemUpdatedEvent];
256 if (eh != null) eh (this, e);
260 protected virtual void OnItemUpdating (FormViewUpdateEventArgs e)
262 if (Events != null) {
263 FormViewUpdateEventHandler eh = (FormViewUpdateEventHandler) Events [ItemUpdatingEvent];
264 if (eh != null) eh (this, e);
269 [WebCategoryAttribute ("Paging")]
270 [DefaultValueAttribute (false)]
271 public virtual bool AllowPaging {
273 object ob = ViewState ["AllowPaging"];
274 if (ob != null) return (bool) ob;
278 ViewState ["AllowPaging"] = value;
283 [UrlPropertyAttribute]
284 [WebCategoryAttribute ("Appearance")]
285 [DefaultValueAttribute ("")]
286 [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
287 public virtual string BackImageUrl {
289 object ob = ViewState ["BackImageUrl"];
290 if (ob != null) return (string) ob;
294 ViewState ["BackImageUrl"] = value;
299 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
300 [BrowsableAttribute (false)]
301 public virtual FormViewRow BottomPagerRow {
304 return bottomPagerRow;
308 [WebCategoryAttribute ("Accessibility")]
309 [DefaultValueAttribute ("")]
310 [LocalizableAttribute (true)]
311 public virtual string Caption {
313 object ob = ViewState ["Caption"];
314 if (ob != null) return (string) ob;
318 ViewState ["Caption"] = value;
323 [WebCategoryAttribute ("Accessibility")]
324 [DefaultValueAttribute (TableCaptionAlign.NotSet)]
325 public virtual TableCaptionAlign CaptionAlign
328 object o = ViewState ["CaptionAlign"];
329 if(o != null) return (TableCaptionAlign) o;
330 return TableCaptionAlign.NotSet;
333 ViewState ["CaptionAlign"] = value;
338 [WebCategoryAttribute ("Layout")]
339 [DefaultValueAttribute (-1)]
340 public virtual int CellPadding
343 object o = ViewState ["CellPadding"];
344 if (o != null) return (int) o;
349 throw new ArgumentOutOfRangeException ("< -1");
350 ViewState ["CellPadding"] = value;
355 [WebCategoryAttribute ("Layout")]
356 [DefaultValueAttribute (0)]
357 public virtual int CellSpacing
360 object o = ViewState ["CellSpacing"];
361 if (o != null) return (int) o;
366 throw new ArgumentOutOfRangeException ("< -1");
367 ViewState["CellSpacing"] = value;
372 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
373 [BrowsableAttribute (false)]
374 public FormViewMode CurrentMode {
380 FormViewMode defaultMode;
382 [DefaultValueAttribute (FormViewMode.ReadOnly)]
383 [WebCategoryAttribute ("Behavior")]
384 public virtual FormViewMode DefaultMode {
394 string[] dataKeyNames;
395 [DefaultValueAttribute (null)]
396 [WebCategoryAttribute ("Data")]
397 [TypeConverter (typeof(StringArrayConverter))]
398 [EditorAttribute ("System.Web.UI.Design.WebControls.DataFieldEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
399 public virtual string[] DataKeyNames
402 if (dataKeyNames == null)
407 dataKeyNames = value;
412 [BrowsableAttribute (false)]
413 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
414 public virtual DataKey DataKey {
421 [DefaultValue (null)]
422 [TemplateContainer (typeof(FormView), BindingDirection.TwoWay)]
423 [PersistenceMode (PersistenceMode.InnerProperty)]
425 public virtual ITemplate EditItemTemplate {
426 get { return editItemTemplate; }
427 set { editItemTemplate = value; RequireBinding (); }
430 [WebCategoryAttribute ("Styles")]
431 [PersistenceMode (PersistenceMode.InnerProperty)]
432 [NotifyParentProperty (true)]
433 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
434 [DefaultValueAttribute (null)]
435 public TableItemStyle EditRowStyle {
437 if (editRowStyle == null) {
438 editRowStyle = new TableItemStyle ();
439 if (IsTrackingViewState)
440 editRowStyle.TrackViewState();
446 [WebCategoryAttribute ("Styles")]
447 [PersistenceMode (PersistenceMode.InnerProperty)]
448 [NotifyParentProperty (true)]
449 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
450 [DefaultValueAttribute (null)]
451 public TableItemStyle EmptyDataRowStyle {
453 if (emptyDataRowStyle == null) {
454 emptyDataRowStyle = new TableItemStyle ();
455 if (IsTrackingViewState)
456 emptyDataRowStyle.TrackViewState();
458 return emptyDataRowStyle;
462 [DefaultValue (null)]
463 [TemplateContainer (typeof(FormView), BindingDirection.OneWay)]
464 [PersistenceMode (PersistenceMode.InnerProperty)]
466 public virtual ITemplate EmptyDataTemplate {
467 get { return emptyDataTemplate; }
468 set { emptyDataTemplate = value; RequireBinding (); }
471 [LocalizableAttribute (true)]
472 [WebCategoryAttribute ("Appearance")]
473 [DefaultValueAttribute ("")]
474 public virtual string EmptyDataText {
476 object ob = ViewState ["EmptyDataText"];
477 if (ob != null) return (string) ob;
481 ViewState ["EmptyDataText"] = value;
486 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
487 [BrowsableAttribute (false)]
488 public virtual FormViewRow FooterRow {
490 EnsureChildControls ();
495 [DefaultValue (null)]
496 [TemplateContainer (typeof(FormView), BindingDirection.OneWay)]
497 [PersistenceMode (PersistenceMode.InnerProperty)]
499 public virtual ITemplate FooterTemplate {
500 get { return footerTemplate; }
501 set { footerTemplate = value; RequireBinding (); }
504 [LocalizableAttribute (true)]
505 [WebCategoryAttribute ("Appearance")]
506 [DefaultValueAttribute ("")]
507 public virtual string FooterText {
509 object ob = ViewState ["FooterText"];
510 if (ob != null) return (string) ob;
514 ViewState ["FooterText"] = value;
519 [WebCategoryAttribute ("Styles")]
520 [PersistenceMode (PersistenceMode.InnerProperty)]
521 [NotifyParentProperty (true)]
522 [DefaultValue (null)]
523 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
524 public TableItemStyle FooterStyle {
526 if (footerStyle == null) {
527 footerStyle = new TableItemStyle ();
528 if (IsTrackingViewState)
529 footerStyle.TrackViewState();
535 [WebCategoryAttribute ("Appearance")]
536 [DefaultValueAttribute (GridLines.None)]
537 public virtual GridLines GridLines {
539 return ((TableStyle) ControlStyle).GridLines;
542 ((TableStyle) ControlStyle).GridLines = value;
546 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
547 [BrowsableAttribute (false)]
548 public virtual FormViewRow HeaderRow {
550 EnsureChildControls ();
555 [WebCategoryAttribute ("Styles")]
556 [PersistenceMode (PersistenceMode.InnerProperty)]
557 [NotifyParentProperty (true)]
558 [DefaultValue (null)]
559 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
560 public TableItemStyle HeaderStyle {
562 if (headerStyle == null) {
563 headerStyle = new TableItemStyle ();
564 if (IsTrackingViewState)
565 headerStyle.TrackViewState();
571 [DefaultValue (null)]
572 [TemplateContainer (typeof(FormView), BindingDirection.OneWay)]
573 [PersistenceMode (PersistenceMode.InnerProperty)]
575 public virtual ITemplate HeaderTemplate {
576 get { return headerTemplate; }
577 set { headerTemplate = value; RequireBinding (); }
580 [LocalizableAttribute (true)]
581 [WebCategoryAttribute ("Appearance")]
582 [DefaultValueAttribute ("")]
583 public virtual string HeaderText {
585 object ob = ViewState ["HeaderText"];
586 if (ob != null) return (string) ob;
590 ViewState ["HeaderText"] = value;
595 [Category ("Layout")]
596 [DefaultValueAttribute (HorizontalAlign.NotSet)]
597 public virtual HorizontalAlign HorizontalAlign {
599 object ob = ViewState ["HorizontalAlign"];
600 if (ob != null) return (HorizontalAlign) ob;
601 return HorizontalAlign.NotSet;
604 ViewState ["HorizontalAlign"] = value;
609 [DefaultValue (null)]
610 [TemplateContainer (typeof(FormView), BindingDirection.TwoWay)]
611 [PersistenceMode (PersistenceMode.InnerProperty)]
613 public virtual ITemplate InsertItemTemplate {
614 get { return insertItemTemplate; }
615 set { insertItemTemplate = value; RequireBinding (); }
618 [WebCategoryAttribute ("Styles")]
619 [PersistenceMode (PersistenceMode.InnerProperty)]
620 [NotifyParentProperty (true)]
621 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
622 [DefaultValueAttribute (null)]
623 public TableItemStyle InsertRowStyle {
625 if (insertRowStyle == null) {
626 insertRowStyle = new TableItemStyle ();
627 if (IsTrackingViewState)
628 insertRowStyle.TrackViewState();
630 return insertRowStyle;
634 [DefaultValue (null)]
635 [TemplateContainer (typeof(FormView), BindingDirection.TwoWay)]
636 [PersistenceMode (PersistenceMode.InnerProperty)]
638 public virtual ITemplate ItemTemplate {
639 get { return itemTemplate; }
640 set { itemTemplate = value; RequireBinding (); }
643 [BrowsableAttribute (false)]
644 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
645 public virtual int PageCount {
647 if (pageCount != 0) return pageCount;
653 [WebCategoryAttribute ("Paging")]
654 [BindableAttribute (true, BindingDirection.OneWay)]
655 [DefaultValueAttribute (0)]
656 public virtual int PageIndex {
661 if (pageIndex == value)
668 [WebCategoryAttribute ("Paging")]
669 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
670 [NotifyParentPropertyAttribute (true)]
671 [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
672 public virtual PagerSettings PagerSettings {
674 if (pagerSettings == null) {
675 pagerSettings = new PagerSettings (this);
676 if (IsTrackingViewState)
677 ((IStateManager)pagerSettings).TrackViewState ();
679 return pagerSettings;
683 [WebCategoryAttribute ("Styles")]
684 [PersistenceMode (PersistenceMode.InnerProperty)]
685 [NotifyParentProperty (true)]
686 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
687 public TableItemStyle PagerStyle {
689 if (pagerStyle == null) {
690 pagerStyle = new TableItemStyle ();
691 if (IsTrackingViewState)
692 pagerStyle.TrackViewState();
699 [DefaultValue (null)]
700 /* DataControlPagerCell isnt specified in the docs */
701 //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
702 [PersistenceMode (PersistenceMode.InnerProperty)]
704 public virtual ITemplate PagerTemplate {
705 get { return pagerTemplate; }
706 set { pagerTemplate = value; RequireBinding (); }
709 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
710 [BrowsableAttribute (false)]
711 public virtual FormViewRow Row {
718 [WebCategoryAttribute ("Styles")]
719 [PersistenceMode (PersistenceMode.InnerProperty)]
720 [NotifyParentProperty (true)]
721 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
722 [DefaultValue (null)]
723 public TableItemStyle RowStyle {
725 if (rowStyle == null) {
726 rowStyle = new TableItemStyle ();
727 if (IsTrackingViewState)
728 rowStyle.TrackViewState();
734 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
735 [BrowsableAttribute (false)]
736 public object SelectedValue {
737 get { return DataKey.Value; }
740 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
741 [BrowsableAttribute (false)]
742 public virtual FormViewRow TopPagerRow {
749 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
750 [BrowsableAttribute (false)]
751 public virtual object DataItem {
758 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
759 [BrowsableAttribute (false)]
760 public int DataItemCount {
761 get { return PageCount; }
764 [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
765 [BrowsableAttribute (false)]
766 public virtual int DataItemIndex {
767 get { return PageIndex; }
770 int IDataItemContainer.DataItemIndex {
771 get { return DataItemIndex; }
774 int IDataItemContainer.DisplayIndex {
775 get { return PageIndex; }
778 public virtual bool IsBindableType (Type type)
780 return type.IsPrimitive || type == typeof (string) || type == typeof (DateTime) || type == typeof (Guid) || type == typeof (Decimal);
783 protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
785 return base.CreateDataSourceSelectArguments ();
788 protected virtual FormViewRow CreateRow (int rowIndex, DataControlRowType rowType, DataControlRowState rowState)
790 FormViewRow row = new FormViewRow (rowIndex, rowType, rowState);
791 OnItemCreated (EventArgs.Empty);
795 void RequireBinding ()
799 RequiresDataBinding = true;
803 protected virtual Table CreateTable ()
805 Table table = new Table ();
806 table.Caption = Caption;
807 table.CaptionAlign = CaptionAlign;
808 table.CellPadding = CellPadding;
809 table.CellSpacing = CellSpacing;
810 table.HorizontalAlign = HorizontalAlign;
811 table.BackImageUrl = BackImageUrl;
816 protected override void EnsureDataBound ()
818 base.EnsureDataBound ();
821 protected override Style CreateControlStyle ()
823 TableStyle style = new TableStyle (ViewState);
824 style.CellSpacing = 0;
828 protected override int CreateChildControls (IEnumerable data, bool dataBinding)
830 PagedDataSource dataSource = new PagedDataSource ();
831 dataSource.DataSource = data;
832 dataSource.AllowPaging = AllowPaging;
833 dataSource.PageSize = 1;
834 dataSource.CurrentPageIndex = PageIndex;
837 DataSourceView view = GetData ();
838 if (view != null && view.CanPage) {
839 dataSource.AllowServerPaging = true;
840 if (view.CanRetrieveTotalRowCount)
841 dataSource.VirtualCount = SelectArguments.TotalRowCount;
845 pageCount = dataSource.DataSourceCount;
846 bool showPager = AllowPaging && (pageCount > 1);
849 table = CreateTable ();
850 Controls.Add (table);
852 if (!Page.IsPostBack)
853 currentMode = DefaultMode;
855 // Gets the current data item
857 IEnumerator e = dataSource.GetEnumerator ();
862 dataItem = e.Current;
865 for (int page = 0; e.MoveNext (); page++ )
866 if (page == PageIndex)
867 dataItem = e.Current;
869 // Main table creation
871 if (HeaderText.Length != 0 || headerTemplate != null) {
872 headerRow = CreateRow (-1, DataControlRowType.Header, DataControlRowState.Normal);
873 InitializeRow (headerRow);
874 table.Rows.Add (headerRow);
877 if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
878 topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
879 InitializePager (topPagerRow, dataSource);
880 table.Rows.Add (topPagerRow);
884 DataControlRowState rstate = GetRowState ();
885 itemRow = CreateRow (0, DataControlRowType.DataRow, rstate);
886 InitializeRow (itemRow);
887 table.Rows.Add (itemRow);
890 if (CurrentMode == FormViewMode.Edit)
891 oldEditValues = new DataKey (new OrderedDictionary ());
892 key = new DataKey (new OrderedDictionary (), DataKeyNames);
895 switch (CurrentMode) {
896 case FormViewMode.Edit:
897 itemRow = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Edit);
899 case FormViewMode.Insert:
900 itemRow = CreateRow (-1, DataControlRowType.DataRow, DataControlRowState.Insert);
903 itemRow = CreateRow (-1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
906 table.Rows.Add (itemRow);
907 InitializeRow (itemRow);
910 if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
911 bottomPagerRow = CreateRow (0, DataControlRowType.Pager, DataControlRowState.Normal);
912 InitializePager (bottomPagerRow, dataSource);
913 table.Rows.Add (bottomPagerRow);
916 if (FooterText.Length != 0 || footerTemplate != null) {
917 footerRow = CreateRow (-1, DataControlRowType.Footer, DataControlRowState.Normal);
918 InitializeRow (footerRow);
919 table.Rows.Add (footerRow);
925 return dataSource.DataSourceCount;
928 DataControlRowState GetRowState ()
930 DataControlRowState rstate = DataControlRowState.Normal;
931 if (CurrentMode == FormViewMode.Edit) rstate |= DataControlRowState.Edit;
932 else if (CurrentMode == FormViewMode.Insert) rstate |= DataControlRowState.Insert;
936 protected virtual void InitializePager (FormViewRow row, PagedDataSource dataSource)
938 TableCell cell = new TableCell ();
941 if (pagerTemplate != null)
942 pagerTemplate.InstantiateIn (cell);
944 cell.Controls.Add (PagerSettings.CreatePagerControl (dataSource.CurrentPageIndex, dataSource.PageCount, pagerStyle));
946 row.Cells.Add (cell);
949 protected virtual void InitializeRow (FormViewRow row)
951 TableCell cell = new TableCell ();
953 if (row.RowType == DataControlRowType.DataRow)
955 if ((row.RowState & DataControlRowState.Edit) != 0) {
956 if (editItemTemplate != null)
957 editItemTemplate.InstantiateIn (cell);
958 } else if ((row.RowState & DataControlRowState.Insert) != 0) {
959 if (insertItemTemplate != null)
960 insertItemTemplate.InstantiateIn (cell);
961 } else if (itemTemplate != null)
962 itemTemplate.InstantiateIn (cell);
964 else if (row.RowType == DataControlRowType.EmptyDataRow)
966 if (emptyDataTemplate != null)
967 emptyDataTemplate.InstantiateIn (cell);
969 cell.Text = EmptyDataText;
971 else if (row.RowType == DataControlRowType.Footer)
973 if (footerTemplate != null)
974 footerTemplate.InstantiateIn (cell);
976 cell.Text = FooterText;
978 else if (row.RowType == DataControlRowType.Header)
980 if (headerTemplate != null)
981 headerTemplate.InstantiateIn (cell);
983 cell.Text = HeaderText;
986 row.Cells.Add (cell);
989 IOrderedDictionary CreateRowDataKey (object dataItem)
991 if (cachedKeyProperties == null) {
992 PropertyDescriptorCollection props = TypeDescriptor.GetProperties (dataItem);
993 cachedKeyProperties = new PropertyDescriptor [DataKeyNames.Length];
994 for (int n=0; n<DataKeyNames.Length; n++) {
995 PropertyDescriptor p = props [DataKeyNames[n]];
997 new InvalidOperationException ("Property '" + DataKeyNames[n] + "' not found in object of type " + dataItem.GetType());
998 cachedKeyProperties [n] = p;
1002 OrderedDictionary dic = new OrderedDictionary ();
1003 foreach (PropertyDescriptor p in cachedKeyProperties)
1004 dic [p.Name] = p.GetValue (dataItem);
1008 IOrderedDictionary GetRowValues (bool includePrimaryKey)
1010 OrderedDictionary dic = new OrderedDictionary ();
1011 ExtractRowValues (dic, includePrimaryKey);
1015 protected virtual void ExtractRowValues (IOrderedDictionary fieldValues, bool includeKeys)
1020 DataControlRowState rowState = Row.RowState;
1021 IBindableTemplate bt;
1023 if ((rowState & DataControlRowState.Insert) != 0)
1024 bt = insertItemTemplate as IBindableTemplate;
1025 else if ((rowState & DataControlRowState.Edit) != 0)
1026 bt = editItemTemplate as IBindableTemplate;
1031 IOrderedDictionary values = bt.ExtractValues (Row.Cells [0]);
1032 foreach (DictionaryEntry e in values) {
1033 if (includeKeys || Array.IndexOf (DataKeyNames, e.Key) == -1)
1034 fieldValues [e.Key] = e.Value;
1039 protected override HtmlTextWriterTag TagKey {
1041 return HtmlTextWriterTag.Table;
1045 public sealed override void DataBind ()
1047 if (CurrentMode == FormViewMode.Insert) {
1048 RequiresDataBinding = false;
1049 PerformDataBinding (new object [] { null });
1053 DataSourceView view = GetData ();
1054 if (AllowPaging && view.CanPage) {
1055 SelectArguments.StartRowIndex = PageIndex;
1056 SelectArguments.MaximumRows = 1;
1057 if (view.CanRetrieveTotalRowCount)
1058 SelectArguments.RetrieveTotalRowCount = true;
1061 cachedKeyProperties = null;
1064 if (pageCount > 0) {
1065 if (CurrentMode == FormViewMode.Edit)
1066 oldEditValues = new DataKey (GetRowValues (true));
1068 oldEditValues = new DataKey (new OrderedDictionary ());
1069 key = new DataKey (CreateRowDataKey (dataItem), DataKeyNames);
1073 protected internal override void PerformDataBinding (IEnumerable data)
1075 base.PerformDataBinding (data);
1079 protected internal virtual void PrepareControlHierarchy ()
1081 throw new NotImplementedException ();
1084 protected internal override void OnInit (EventArgs e)
1086 Page.RegisterRequiresControlState (this);
1090 protected override bool OnBubbleEvent (object source, EventArgs e)
1092 FormViewCommandEventArgs args = e as FormViewCommandEventArgs;
1094 OnItemCommand (args);
1095 ProcessEvent (args.CommandName, args.CommandArgument as string);
1097 return base.OnBubbleEvent (source, e);
1100 void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
1102 RaisePostBackEvent (eventArgument);
1105 protected virtual void RaisePostBackEvent (string eventArgument)
1107 int i = eventArgument.IndexOf ('$');
1109 ProcessEvent (eventArgument.Substring (0, i), eventArgument.Substring (i + 1));
1111 ProcessEvent (eventArgument, null);
1114 void ProcessEvent (string eventName, string param)
1118 case DataControlCommands.PageCommandName:
1121 case DataControlCommands.FirstPageCommandArgument:
1124 case DataControlCommands.LastPageCommandArgument:
1125 newIndex = PageCount - 1;
1127 case DataControlCommands.NextPageCommandArgument:
1128 newIndex = PageIndex + 1;
1130 case DataControlCommands.PreviousPageCommandArgument:
1131 newIndex = PageIndex - 1;
1135 int.TryParse (param, out paramIndex);
1136 newIndex = paramIndex - 1;
1139 ShowPage (newIndex);
1142 case DataControlCommands.FirstPageCommandArgument:
1146 case DataControlCommands.LastPageCommandArgument:
1147 ShowPage (PageCount - 1);
1150 case DataControlCommands.NextPageCommandArgument:
1151 if (PageIndex < PageCount - 1)
1152 ShowPage (PageIndex + 1);
1155 case DataControlCommands.PreviousPageCommandArgument:
1157 ShowPage (PageIndex - 1);
1160 case DataControlCommands.EditCommandName:
1161 ChangeMode (FormViewMode.Edit);
1164 case DataControlCommands.NewCommandName:
1165 ChangeMode (FormViewMode.Insert);
1168 case DataControlCommands.UpdateCommandName:
1169 UpdateItem (param, true);
1172 case DataControlCommands.CancelCommandName:
1176 case DataControlCommands.DeleteCommandName:
1180 case DataControlCommands.InsertCommandName:
1186 void ShowPage (int newIndex)
1188 FormViewPageEventArgs args = new FormViewPageEventArgs (newIndex);
1189 OnPageIndexChanging (args);
1191 newIndex = args.NewPageIndex;
1192 if (newIndex < 0 || newIndex >= PageCount)
1195 PageIndex = newIndex;
1196 OnPageIndexChanged (EventArgs.Empty);
1200 public void ChangeMode (FormViewMode newMode)
1202 FormViewModeEventArgs args = new FormViewModeEventArgs (newMode, false);
1203 OnModeChanging (args);
1205 currentMode = args.NewMode;
1206 OnModeChanged (EventArgs.Empty);
1213 FormViewModeEventArgs args = new FormViewModeEventArgs (FormViewMode.ReadOnly, true);
1214 OnModeChanging (args);
1220 public virtual void UpdateItem (bool causesValidation)
1222 UpdateItem (null, causesValidation);
1225 void UpdateItem (string param, bool causesValidation)
1227 if (causesValidation)
1230 if (currentMode != FormViewMode.Edit) throw new NotSupportedException ();
1232 currentEditOldValues = oldEditValues.Values;
1233 currentEditRowKeys = DataKey.Values;
1234 currentEditNewValues = GetRowValues (false);
1236 FormViewUpdateEventArgs args = new FormViewUpdateEventArgs (param, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1237 OnItemUpdating (args);
1239 DataSourceView view = GetData ();
1241 throw new HttpException ("The DataSourceView associated to data bound control was null");
1243 view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
1249 bool UpdateCallback (int recordsAffected, Exception exception)
1251 FormViewUpdatedEventArgs dargs = new FormViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
1252 OnItemUpdated (dargs);
1254 if (!dargs.KeepInEditMode)
1257 return dargs.ExceptionHandled;
1260 public virtual void InsertItem (bool causesValidation)
1262 InsertItem (null, causesValidation);
1265 void InsertItem (string param, bool causesValidation)
1267 if (causesValidation)
1270 if (currentMode != FormViewMode.Insert) throw new NotSupportedException ();
1272 currentEditNewValues = GetRowValues (true);
1273 FormViewInsertEventArgs args = new FormViewInsertEventArgs (param, currentEditNewValues);
1274 OnItemInserting (args);
1276 DataSourceView view = GetData ();
1278 throw new HttpException ("The DataSourceView associated to data bound control was null");
1280 view.Insert (currentEditNewValues, new DataSourceViewOperationCallback (InsertCallback));
1286 bool InsertCallback (int recordsAffected, Exception exception)
1288 FormViewInsertedEventArgs dargs = new FormViewInsertedEventArgs (recordsAffected, exception, currentEditNewValues);
1289 OnItemInserted (dargs);
1291 if (!dargs.KeepInInsertMode)
1294 return dargs.ExceptionHandled;
1297 public virtual void DeleteItem ()
1299 currentEditRowKeys = DataKey.Values;
1300 currentEditNewValues = GetRowValues (true);
1302 FormViewDeleteEventArgs args = new FormViewDeleteEventArgs (PageIndex, currentEditRowKeys, currentEditNewValues);
1303 OnItemDeleting (args);
1306 if (PageIndex == PageCount - 1)
1311 DataSourceView view = GetData ();
1312 if (view != null && view.CanDelete)
1313 view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
1315 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
1316 OnItemDeleted (dargs);
1321 bool DeleteCallback (int recordsAffected, Exception exception)
1323 FormViewDeletedEventArgs dargs = new FormViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
1324 OnItemDeleted (dargs);
1325 return dargs.ExceptionHandled;
1333 void EndRowEdit (bool switchToDefaultMode)
1335 if (switchToDefaultMode)
1336 ChangeMode (DefaultMode);
1337 oldEditValues = new DataKey (new OrderedDictionary ());
1338 currentEditRowKeys = null;
1339 currentEditOldValues = null;
1340 currentEditNewValues = null;
1344 protected internal override void LoadControlState (object ob)
1346 if (ob == null) return;
1347 object[] state = (object[]) ob;
1348 base.LoadControlState (state[0]);
1349 pageIndex = (int) state[1];
1350 pageCount = (int) state[2];
1351 currentMode = (FormViewMode) state[3];
1352 defaultMode = (FormViewMode) state[4];
1353 dataKeyNames = (string[]) state[5];
1356 protected internal override object SaveControlState ()
1358 object bstate = base.SaveControlState ();
1359 return new object[] {
1360 bstate, pageIndex, pageCount, currentMode, defaultMode, dataKeyNames
1364 protected override void TrackViewState()
1366 base.TrackViewState();
1367 if (pagerSettings != null) ((IStateManager)pagerSettings).TrackViewState();
1368 if (footerStyle != null) ((IStateManager)footerStyle).TrackViewState();
1369 if (headerStyle != null) ((IStateManager)headerStyle).TrackViewState();
1370 if (pagerStyle != null) ((IStateManager)pagerStyle).TrackViewState();
1371 if (rowStyle != null) ((IStateManager)rowStyle).TrackViewState();
1372 if (editRowStyle != null) ((IStateManager)editRowStyle).TrackViewState();
1373 if (insertRowStyle != null) ((IStateManager)insertRowStyle).TrackViewState();
1374 if (emptyDataRowStyle != null) ((IStateManager)emptyDataRowStyle).TrackViewState();
1375 if (key != null) ((IStateManager)key).TrackViewState();
1378 protected override object SaveViewState()
1380 object[] states = new object [14];
1381 states[0] = base.SaveViewState();
1382 states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
1383 states[4] = (footerStyle == null ? null : ((IStateManager)footerStyle).SaveViewState());
1384 states[5] = (headerStyle == null ? null : ((IStateManager)headerStyle).SaveViewState());
1385 states[6] = (pagerStyle == null ? null : ((IStateManager)pagerStyle).SaveViewState());
1386 states[7] = (rowStyle == null ? null : ((IStateManager)rowStyle).SaveViewState());
1387 states[8] = (insertRowStyle == null ? null : ((IStateManager)insertRowStyle).SaveViewState());
1388 states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
1389 states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
1390 states[11] = (key == null ? null : ((IStateManager)key).SaveViewState());
1391 states[12] = (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState());
1393 for (int i = states.Length - 1; i >= 0; i--) {
1394 if (states [i] != null)
1401 protected override void LoadViewState (object savedState)
1403 if (savedState == null) {
1404 base.LoadViewState (null);
1408 object [] states = (object []) savedState;
1410 base.LoadViewState (states[0]);
1411 EnsureChildControls ();
1413 if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
1414 if (states[4] != null) ((IStateManager)FooterStyle).LoadViewState (states[4]);
1415 if (states[5] != null) ((IStateManager)HeaderStyle).LoadViewState (states[5]);
1416 if (states[6] != null) ((IStateManager)PagerStyle).LoadViewState (states[6]);
1417 if (states[7] != null) ((IStateManager)RowStyle).LoadViewState (states[7]);
1418 if (states[8] != null) ((IStateManager)InsertRowStyle).LoadViewState (states[8]);
1419 if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
1420 if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
1421 if (states[11] != null && DataKey != null) ((IStateManager)DataKey).LoadViewState (states[11]);
1422 if (states[12] != null && oldEditValues != null) ((IStateManager)oldEditValues).LoadViewState (states[12]);
1425 protected internal override void Render (HtmlTextWriter writer)
1427 switch (GridLines) {
1428 case GridLines.Horizontal:
1429 writer.AddAttribute (HtmlTextWriterAttribute.Rules, "rows");
1430 writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
1432 case GridLines.Vertical:
1433 writer.AddAttribute (HtmlTextWriterAttribute.Rules, "cols");
1434 writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
1436 case GridLines.Both:
1437 writer.AddAttribute (HtmlTextWriterAttribute.Rules, "all");
1438 writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
1441 writer.AddAttribute (HtmlTextWriterAttribute.Border, "0");
1445 writer.AddAttribute (HtmlTextWriterAttribute.Cellspacing, "0");
1446 if (!string.IsNullOrEmpty (ControlStyle.CssClass))
1447 writer.AddAttribute (HtmlTextWriterAttribute.Class, ControlStyle.CssClass);
1449 table.ControlStyle.MergeWith (ControlStyle);
1450 table.RenderBeginTag (writer);
1452 foreach (FormViewRow row in table.Rows)
1454 switch (row.RowType) {
1455 case DataControlRowType.Header:
1456 if (headerStyle != null)headerStyle.AddAttributesToRender (writer, row);
1458 case DataControlRowType.Footer:
1459 if (footerStyle != null) footerStyle.AddAttributesToRender (writer, row);
1461 case DataControlRowType.Pager:
1462 if (pagerStyle != null) pagerStyle.AddAttributesToRender (writer, row);
1464 case DataControlRowType.EmptyDataRow:
1465 if (emptyDataRowStyle != null) emptyDataRowStyle.AddAttributesToRender (writer, row);
1468 if (rowStyle != null) rowStyle.AddAttributesToRender (writer, row);
1472 if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null)
1473 editRowStyle.AddAttributesToRender (writer, row);
1474 if ((row.RowState & DataControlRowState.Insert) != 0 && insertRowStyle != null)
1475 insertRowStyle.AddAttributesToRender (writer, row);
1477 row.RenderBeginTag (writer);
1479 for (int n=0; n<row.Cells.Count; n++)
1480 row.Cells[n].Render (writer);
1482 row.RenderEndTag (writer);
1484 table.RenderEndTag (writer);
1487 PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
1489 Control ctrl = control as Control;
1490 return new PostBackOptions(ctrl);