New test.
[mono.git] / mcs / class / System.Web / System.Web.UI.WebControls / GridView.cs
index 0c02f3a3b2d096a2f03419fe2d42f25416bb456c..9417999257d932a3bc51b5849ff17b635a7232ac 100644 (file)
@@ -40,17 +40,16 @@ using System.Reflection;
 
 namespace System.Web.UI.WebControls
 {
+       [SupportsEventValidation]
        [DesignerAttribute ("System.Web.UI.Design.WebControls.GridViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
        [ControlValuePropertyAttribute ("SelectedValue")]
        [DefaultEventAttribute ("SelectedIndexChanged")]
        [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
-       public class GridView: CompositeDataBoundControl, ICallbackEventHandler, ICallbackContainer
+       public class GridView: CompositeDataBoundControl, ICallbackEventHandler, ICallbackContainer, IPostBackEventHandler, IPostBackContainer
        {
                Table table;
                GridViewRowCollection rows;
-               GridViewRow headerRow;
-               GridViewRow footerRow;
                GridViewRow bottomPagerRow;
                GridViewRow topPagerRow;
                
@@ -75,9 +74,11 @@ namespace System.Web.UI.WebControls
                TableItemStyle pagerStyle;
                TableItemStyle rowStyle;
                TableItemStyle selectedRowStyle;
+               ArrayList _dataKeyArrayList;
                DataKeyArray keys;
                DataKey oldEditValues;
                AutoGeneratedFieldProperties[] autoFieldProperties;
+               string [] dataKeyNames = null;
                readonly string[] emptyKeys = new string[0];
                
                private static readonly object PageIndexChangedEvent = new object();
@@ -98,7 +99,6 @@ namespace System.Web.UI.WebControls
                
                // Control state
                int pageIndex;
-               int pageCount = -1;
                int selectedIndex = -1;
                int editIndex = -1;
                SortDirection sortDirection = SortDirection.Ascending;
@@ -306,7 +306,7 @@ namespace System.Web.UI.WebControls
                
                [WebCategoryAttribute ("Paging")]
                [DefaultValueAttribute (false)]
-               public bool AllowPaging {
+               public virtual bool AllowPaging {
                        get {
                                object ob = ViewState ["AllowPaging"];
                                if (ob != null) return (bool) ob;
@@ -320,7 +320,7 @@ namespace System.Web.UI.WebControls
                
                [WebCategoryAttribute ("Behavior")]
                [DefaultValueAttribute (false)]
-               public bool AllowSorting {
+               public virtual bool AllowSorting {
                        get {
                                object ob = ViewState ["AllowSorting"];
                                if (ob != null) return (bool) ob;
@@ -332,11 +332,11 @@ namespace System.Web.UI.WebControls
                        }
                }
                
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle AlternatingRowStyle {
+               public TableItemStyle AlternatingRowStyle {
                        get {
                                if (alternatingRowStyle == null) {
                                        alternatingRowStyle = new TableItemStyle ();
@@ -409,13 +409,12 @@ namespace System.Web.UI.WebControls
                [EditorAttribute ("System.Web.UI.Design.ImageUrlEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
                public virtual string BackImageUrl {
                        get {
-                               object ob = ViewState ["BackImageUrl"];
-                               if (ob != null) return (string) ob;
-                               return string.Empty;
+                               if (ControlStyleCreated)
+                                       return ((TableStyle) ControlStyle).BackImageUrl;
+                               return String.Empty;
                        }
                        set {
-                               ViewState ["BackImageUrl"] = value;
-                               RequireBinding ();
+                               ((TableStyle) ControlStyle).BackImageUrl = value;
                        }
                }
 
@@ -431,7 +430,7 @@ namespace System.Web.UI.WebControls
                [WebCategoryAttribute ("Accessibility")]
                [DefaultValueAttribute ("")]
                [LocalizableAttribute (true)]
-               public string Caption {
+               public virtual string Caption {
                        get {
                                object ob = ViewState ["Caption"];
                                if (ob != null) return (string) ob;
@@ -463,13 +462,12 @@ namespace System.Web.UI.WebControls
                public virtual int CellPadding
                {
                        get {
-                               object o = ViewState ["CellPadding"];
-                               if (o != null) return (int) o;
+                               if (ControlStyleCreated)
+                                       return ((TableStyle) ControlStyle).CellPadding;
                                return -1;
                        }
                        set {
-                               ViewState ["CellPadding"] = value;
-                               RequireBinding ();
+                               ((TableStyle) ControlStyle).CellPadding = value;
                        }
                }
 
@@ -478,13 +476,12 @@ namespace System.Web.UI.WebControls
                public virtual int CellSpacing
                {
                        get {
-                               object o = ViewState ["CellSpacing"];
-                               if (o != null) return (int) o;
+                               if (ControlStyleCreated)
+                                       return ((TableStyle) ControlStyle).CellSpacing;
                                return 0;
                        }
                        set {
-                               ViewState ["CellSpacing"] = value;
-                               RequireBinding ();
+                               ((TableStyle) ControlStyle).CellSpacing = value;
                        }
                }
                
@@ -512,42 +509,66 @@ namespace System.Web.UI.WebControls
                public virtual string[] DataKeyNames
                {
                        get {
-                               object o = ViewState ["DataKeyNames"];
-                               if (o != null) return (string[]) o;
+                               if (dataKeyNames != null)
+                                       return dataKeyNames;
                                return emptyKeys;
                        }
                        set {
-                               ViewState ["DataKeyNames"] = value;
+                               dataKeyNames = value;
                                RequireBinding ();
                        }
                }
+
+               ArrayList DataKeyArrayList {
+                       get {
+                               if (_dataKeyArrayList == null) {
+                                       _dataKeyArrayList = new ArrayList ();
+                               }
+                               return _dataKeyArrayList;
+                       }
+               }
                
                [BrowsableAttribute (false)]
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
                public virtual DataKeyArray DataKeys {
                        get {
-                               EnsureDataBound ();
+                               if (keys == null) {
+                                       keys = new DataKeyArray (DataKeyArrayList);
+                                       if (IsTrackingViewState)
+                                               ((IStateManager) keys).TrackViewState ();
+                               }
                                return keys;
                        }
                }
 
+               DataKey OldEditValues {
+                       get {
+                               if (oldEditValues == null) {
+                                       oldEditValues = new DataKey (new OrderedDictionary ());
+                               }
+                               return oldEditValues;
+                       }
+               }
+
                [WebCategoryAttribute ("Misc")]
                [DefaultValueAttribute (-1)]
-               public int EditIndex {
+               public virtual int EditIndex {
                        get {
                                return editIndex;
                        }
                        set {
+                               if (value == editIndex)
+                                       return;
                                editIndex = value;
                                RequireBinding ();
                        }
                }
        
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle EditRowStyle {
+               public TableItemStyle EditRowStyle {
                        get {
                                if (editRowStyle == null) {
                                        editRowStyle = new TableItemStyle ();
@@ -558,11 +579,11 @@ namespace System.Web.UI.WebControls
                        }
                }
                
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle EmptyDataRowStyle {
+               public TableItemStyle EmptyDataRowStyle {
                        get {
                                if (emptyDataRowStyle == null) {
                                        emptyDataRowStyle = new TableItemStyle ();
@@ -574,10 +595,10 @@ namespace System.Web.UI.WebControls
                }
                
                [DefaultValue (null)]
-               [TemplateContainer (typeof(GridView), BindingDirection.OneWay)]
+               [TemplateContainer (typeof(GridViewRow), BindingDirection.OneWay)]
                [PersistenceMode (PersistenceMode.InnerProperty)]
-           [Browsable (false)]
-               public ITemplate EmptyDataTemplate {
+               [Browsable (false)]
+               public virtual ITemplate EmptyDataTemplate {
                        get { return emptyDataTemplate; }
                        set { emptyDataTemplate = value; RequireBinding (); }
                }
@@ -615,18 +636,30 @@ namespace System.Web.UI.WebControls
                [BrowsableAttribute (false)]
                public virtual GridViewRow FooterRow {
                        get {
-                               if (footerRow == null)
-                                       footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
-                               return footerRow;
+                               if (table != null) {
+                                       for (int index = table.Rows.Count - 1; index >= 0; index--) {
+                                               GridViewRow row = (GridViewRow) table.Rows [index];
+                                               switch (row.RowType) {
+                                               case DataControlRowType.Separator:
+                                               case DataControlRowType.Pager:
+                                                       continue;
+                                               case DataControlRowType.Footer:
+                                                       return row;
+                                               default:
+                                                       break;
+                                               }
+                                       }
+                               }
+                               return null;
                        }
                }
        
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DefaultValue (null)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle FooterStyle {
+               public TableItemStyle FooterStyle {
                        get {
                                if (footerStyle == null) {
                                        footerStyle = new TableItemStyle ();
@@ -641,12 +674,12 @@ namespace System.Web.UI.WebControls
                [DefaultValueAttribute (GridLines.Both)]
                public virtual GridLines GridLines {
                        get {
-                               object ob = ViewState ["GridLines"];
-                               if (ob != null) return (GridLines) ob;
+                               if (ControlStyleCreated)
+                                       return ((TableStyle) ControlStyle).GridLines;
                                return GridLines.Both;
                        }
                        set {
-                               ViewState ["GridLines"] = value;
+                               ((TableStyle) ControlStyle).GridLines = value;
                        }
                }
 
@@ -654,18 +687,30 @@ namespace System.Web.UI.WebControls
                [BrowsableAttribute (false)]
                public virtual GridViewRow HeaderRow {
                        get {
-                               if (headerRow == null)
-                                       headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
-                               return headerRow;
+                               if (table != null) {
+                                       for (int index = 0, total = table.Rows.Count; index < total; index++) {
+                                               GridViewRow row = (GridViewRow) table.Rows [index];
+                                               switch (row.RowType) {
+                                               case DataControlRowType.Separator:
+                                               case DataControlRowType.Pager:
+                                                       continue;
+                                               case DataControlRowType.Header:
+                                                       return row;
+                                               default:
+                                                       break;
+                                               }
+                                       }
+                               }
+                               return null;
                        }
                }
        
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DefaultValue (null)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle HeaderStyle {
+               public TableItemStyle HeaderStyle {
                        get {
                                if (headerStyle == null) {
                                        headerStyle = new TableItemStyle ();
@@ -676,37 +721,40 @@ namespace System.Web.UI.WebControls
                        }
                }
                
+               [Category ("Layout")]
                [DefaultValueAttribute (HorizontalAlign.NotSet)]
                public virtual HorizontalAlign HorizontalAlign {
                        get {
-                               object ob = ViewState ["HorizontalAlign"];
-                               if (ob != null) return (HorizontalAlign) ob;
+                               if (ControlStyleCreated)
+                                       return ((TableStyle) ControlStyle).HorizontalAlign;
                                return HorizontalAlign.NotSet;
                        }
                        set {
-                               ViewState ["HorizontalAlign"] = value;
-                               RequireBinding ();
+                               ((TableStyle) ControlStyle).HorizontalAlign = value;
                        }
                }
 
                [BrowsableAttribute (false)]
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
-               public int PageCount {
+               public virtual int PageCount {
                        get {
-                               if (pageCount != -1) return pageCount;
-                               EnsureDataBound ();
-                               return pageCount;
+                               return ViewState.GetInt ("PageCount", 0);
+                       }
+                       private set {
+                               ViewState ["PageCount"] = value;
                        }
                }
 
                [WebCategoryAttribute ("Paging")]
                [BrowsableAttribute (true)]
                [DefaultValueAttribute (0)]
-               public int PageIndex {
+               public virtual int PageIndex {
                        get {
                                return pageIndex;
                        }
                        set {
+                               if (value == pageIndex)
+                                       return;
                                pageIndex = value;
                                RequireBinding ();
                        }
@@ -714,7 +762,7 @@ namespace System.Web.UI.WebControls
        
                [DefaultValueAttribute (10)]
                [WebCategoryAttribute ("Paging")]
-               public int PageSize {
+               public virtual int PageSize {
                        get {
                                object ob = ViewState ["PageSize"];
                                if (ob != null) return (int) ob;
@@ -730,7 +778,7 @@ namespace System.Web.UI.WebControls
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Content)]
                [NotifyParentPropertyAttribute (true)]
                [PersistenceModeAttribute (PersistenceMode.InnerProperty)]
-               public PagerSettings PagerSettings {
+               public virtual PagerSettings PagerSettings {
                        get {
                                if (pagerSettings == null) {
                                        pagerSettings = new PagerSettings (this);
@@ -741,11 +789,11 @@ namespace System.Web.UI.WebControls
                        }
                }
        
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle PagerStyle {
+               public TableItemStyle PagerStyle {
                        get {
                                if (pagerStyle == null) {
                                        pagerStyle = new TableItemStyle ();
@@ -758,17 +806,18 @@ namespace System.Web.UI.WebControls
                
                
                [DefaultValue (null)]
-               [TemplateContainer (typeof(GridView), BindingDirection.OneWay)]
+               /* DataControlPagerCell isnt specified in the docs */
+               //[TemplateContainer (typeof(DataControlPagerCell), BindingDirection.OneWay)]
                [PersistenceMode (PersistenceMode.InnerProperty)]
-           [Browsable (false)]
-               public ITemplate PagerTemplate {
+               [Browsable (false)]
+               public virtual ITemplate PagerTemplate {
                        get { return pagerTemplate; }
                        set { pagerTemplate = value; RequireBinding (); }
                }
                
                [DefaultValueAttribute ("")]
                [WebCategoryAttribute ("Accessibility")]
-//             [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
+               //              [TypeConverterAttribute (typeof(System.Web.UI.Design.DataColumnSelectionConverter)]
                public virtual string RowHeaderColumn {
                        get {
                                object ob = ViewState ["RowHeaderColumn"];
@@ -785,16 +834,18 @@ namespace System.Web.UI.WebControls
                [BrowsableAttribute (false)]
                public virtual GridViewRowCollection Rows {
                        get {
-                               EnsureDataBound ();
+                               EnsureChildControls ();
+                               if (rows == null)
+                                       rows = new GridViewRowCollection (new ArrayList ());
                                return rows;
                        }
                }
                
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle RowStyle {
+               public TableItemStyle RowStyle {
                        get {
                                if (rowStyle == null) {
                                        rowStyle = new TableItemStyle ();
@@ -809,6 +860,9 @@ namespace System.Web.UI.WebControls
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
                public virtual DataKey SelectedDataKey {
                        get {
+                               if (keys == null)
+                                       throw new InvalidOperationException ("DataKeys");
+
                                if (selectedIndex >= 0 && selectedIndex < DataKeys.Count) {
                                        return DataKeys [selectedIndex];
                                } else
@@ -818,18 +872,18 @@ namespace System.Web.UI.WebControls
                
                [BindableAttribute (true)]
                [DefaultValueAttribute (-1)]
-               public int SelectedIndex {
+               public virtual int SelectedIndex {
                        get {
                                return selectedIndex;
                        }
                        set {
-                               if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
+                               if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
                                        int oldIndex = selectedIndex;
                                        selectedIndex = -1;
                                        Rows [oldIndex].RowState = GetRowState (oldIndex);
                                }
                                selectedIndex = value;
-                               if (selectedIndex >= 0 && selectedIndex < Rows.Count) {
+                               if (Rows != null && selectedIndex >= 0 && selectedIndex < Rows.Count) {
                                        Rows [selectedIndex].RowState = GetRowState (selectedIndex);
                                }
                        }
@@ -846,11 +900,11 @@ namespace System.Web.UI.WebControls
                        }
                }
                
-           [WebCategoryAttribute ("Styles")]
+               [WebCategoryAttribute ("Styles")]
                [PersistenceMode (PersistenceMode.InnerProperty)]
                [NotifyParentProperty (true)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
-               public virtual TableItemStyle SelectedRowStyle {
+               public TableItemStyle SelectedRowStyle {
                        get {
                                if (selectedRowStyle == null) {
                                        selectedRowStyle = new TableItemStyle ();
@@ -862,7 +916,7 @@ namespace System.Web.UI.WebControls
                }
                
                [BrowsableAttribute (false)]
-               public virtual object SelectedValue {
+               public object SelectedValue {
                        get {
                                if (SelectedDataKey != null)
                                        return SelectedDataKey.Value;
@@ -905,12 +959,28 @@ namespace System.Web.UI.WebControls
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
                public virtual SortDirection SortDirection {
                        get { return sortDirection; }
+                       private set {
+                               if (sortDirection == value)
+                                       return;
+                               sortDirection = value;
+                               RequireBinding ();
+                       }
                }
                
                [BrowsableAttribute (false)]
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
                public virtual string SortExpression {
-                       get { return sortExpression; }
+                       get {
+                               if (sortExpression == null)
+                                       return String.Empty;
+                               return sortExpression;
+                       }
+                       private set {
+                               if (sortExpression == value)
+                                       return;
+                               sortExpression = value;
+                               RequireBinding ();
+                       }
                }
                
                [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
@@ -941,9 +1011,33 @@ namespace System.Web.UI.WebControls
                        return type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) || type == typeof(Guid);
                }
                
+               // MSDN: The CreateDataSourceSelectArguments method is a helper method called by 
+               // the GridView control to create the DataSourceSelectArguments object that 
+               // contains the arguments passed to the data source. In this implementation, 
+               // the DataSourceSelectArguments object contains the arguments for paging operations.
                protected override DataSourceSelectArguments CreateDataSourceSelectArguments ()
                {
-                       return base.CreateDataSourceSelectArguments ();
+                       DataSourceSelectArguments arg = DataSourceSelectArguments.Empty;
+                       DataSourceView view= GetData();
+                       if (AllowPaging && view.CanPage) {
+                               arg.StartRowIndex = PageIndex * PageSize;
+                               if (view.CanRetrieveTotalRowCount) {
+                                       arg.RetrieveTotalRowCount = true;
+                                       arg.MaximumRows = PageSize;
+                               }
+                               else {
+                                       arg.MaximumRows = -1;
+                               }
+                       }
+
+                       if (IsBoundUsingDataSourceID && !String.IsNullOrEmpty (sortExpression)) {
+                               if (sortDirection == SortDirection.Ascending)
+                                       arg.SortExpression = sortExpression;
+                               else
+                                       arg.SortExpression = sortExpression + " DESC";
+                       }
+                       
+                       return arg;
                }
                
                protected virtual ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
@@ -957,6 +1051,8 @@ namespace System.Web.UI.WebControls
                                field.ShowSelectButton = AutoGenerateSelectButton;
                                fields.Add (field);
                        }
+
+                       fields.AddRange (Columns);
                        
                        if (AutoGenerateColumns) {
                                if (useDataSource)
@@ -968,8 +1064,6 @@ namespace System.Web.UI.WebControls
                                }
                        }
                        
-                       fields.AddRange (Columns);
-                       
                        return fields;
                }
                
@@ -992,9 +1086,9 @@ namespace System.Web.UI.WebControls
                                object fitem = null;
                                prop_type = null;
                                PropertyInfo prop_item =  source.DataSource.GetType().GetProperty("Item",
-                                                 BindingFlags.Instance | BindingFlags.Static |
-                                                 BindingFlags.Public, null, null,
-                                                 new Type[] { typeof(int) }, null);
+                                                                                                 BindingFlags.Instance | BindingFlags.Static |
+                                                                                                 BindingFlags.Public, null, null,
+                                                                                                 new Type[] { typeof(int) }, null);
                                
                                if (prop_item != null) {
                                        prop_type = prop_item.PropertyType;
@@ -1048,7 +1142,6 @@ namespace System.Web.UI.WebControls
                protected virtual GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
                {
                        GridViewRow row = new GridViewRow (rowIndex, dataSourceIndex, rowType, rowState);
-                       OnRowCreated (new GridViewRowEventArgs (row));
                        return row;
                }
                
@@ -1056,24 +1149,25 @@ namespace System.Web.UI.WebControls
                {
                        if (Initialized) {
                                RequiresDataBinding = true;
-                               pageCount = -1;
                        }
                }
                
                protected virtual Table CreateChildTable ()
                {
-                       Table table = new Table ();
-                       table.Caption = Caption;
-                       table.CaptionAlign = CaptionAlign;
-                       table.CellPadding = CellPadding;
-                       table.CellSpacing = CellSpacing;
-                       table.HorizontalAlign = HorizontalAlign;
-                       table.BackImageUrl = BackImageUrl;
-                       return table;
+                       return new ContainedTable (this);
                }
        
                protected override int CreateChildControls (IEnumerable data, bool dataBinding)
                {
+                       // clear GridView
+                       Controls.Clear ();
+                       table = null;
+                       rows = null;
+                       
+                       if (data == null) {
+                               return 0;
+                       }
+
                        PagedDataSource dataSource;
 
                        if (dataBinding) {
@@ -1087,17 +1181,12 @@ namespace System.Web.UI.WebControls
                                        dataSource.CurrentPageIndex = PageIndex;
                                        if (view.CanPage) {
                                                dataSource.AllowServerPaging = true;
-                                               if (view.CanRetrieveTotalRowCount)
+                                               if (SelectArguments.RetrieveTotalRowCount)
                                                        dataSource.VirtualCount = SelectArguments.TotalRowCount;
-                                               else {
-                                                       dataSource.DataSourceView = view;
-                                                       dataSource.DataSourceSelectArguments = SelectArguments;
-                                                       dataSource.SetItemCountFromPageIndex (PageIndex + PagerSettings.PageButtonCount);
-                                               }
                                        }
                                }
                                
-                               pageCount = dataSource.PageCount;
+                               PageCount = dataSource.PageCount;
                        }
                        else
                        {
@@ -1110,14 +1199,15 @@ namespace System.Web.UI.WebControls
                                }
                        }
 
+                       if (dataSource.DataSourceCount == 0)
+                               return 0;
+
                        bool showPager = AllowPaging && (PageCount > 1);
                        
-                       Controls.Clear ();
                        table = CreateChildTable ();
                        Controls.Add (table);
                                
                        ArrayList list = new ArrayList ();
-                       ArrayList keyList = new ArrayList ();
                        
                        // Creates the set of fields to show
                        
@@ -1136,12 +1226,16 @@ namespace System.Web.UI.WebControls
                        if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
                                topPagerRow = CreatePagerRow (fields.Length, dataSource);
                                table.Rows.Add (topPagerRow);
+                               OnRowCreated (new GridViewRowEventArgs (topPagerRow));
                        }
 
-                       if (ShowHeader) {
-                               headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
-                               table.Rows.Add (headerRow);
-                               InitializeRow (headerRow, fields);
+                       GridViewRow headerRow = CreateRow (0, 0, DataControlRowType.Header, DataControlRowState.Normal);
+                       table.Rows.Add (headerRow);
+                       InitializeRow (headerRow, fields);
+                       OnRowCreated (new GridViewRowEventArgs (headerRow));
+                       if (dataBinding) {
+                               headerRow.DataBind ();
+                               OnRowDataBound (new GridViewRowEventArgs (headerRow));
                        }
                        
                        foreach (object obj in dataSource) {
@@ -1151,44 +1245,56 @@ namespace System.Web.UI.WebControls
                                list.Add (row);
                                table.Rows.Add (row);
                                InitializeRow (row, fields);
+                               OnRowCreated (new GridViewRowEventArgs (row));
                                if (dataBinding) {
-//                                     row.DataBind ();
+                                       row.DataBind ();
                                        OnRowDataBound (new GridViewRowEventArgs (row));
                                        if (EditIndex == row.RowIndex)
                                                oldEditValues = new DataKey (GetRowValues (row, false, true));
-                                       keyList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
-                               } else {
-                                       if (EditIndex == row.RowIndex)
-                                               oldEditValues = new DataKey (new OrderedDictionary ());
-                                       keyList.Add (new DataKey (new OrderedDictionary (), DataKeyNames));
-                               }
+                                       DataKeyArrayList.Add (new DataKey (CreateRowDataKey (row), DataKeyNames));
+                               } 
 
                                if (list.Count >= PageSize)
                                        break;
                        }
-                       
-                       if (list.Count == 0)
-                               table.Rows.Add (CreateEmptyrRow (fields.Length));
 
-                       if (ShowFooter) {
-                               footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
-                               table.Rows.Add (footerRow);
-                               InitializeRow (footerRow, fields);
+                       if (list.Count == 0) {
+                               GridViewRow emptyRow = CreateEmptyrRow (fields.Length);
+                               table.Rows.Add (emptyRow);
+                               OnRowCreated (new GridViewRowEventArgs (emptyRow));
+                               if (dataBinding) {
+                                       emptyRow.DataBind ();
+                                       OnRowDataBound (new GridViewRowEventArgs (emptyRow));
+                               }
+                       }
+
+                       GridViewRow footerRow = CreateRow (0, 0, DataControlRowType.Footer, DataControlRowState.Normal);
+                       table.Rows.Add (footerRow);
+                       InitializeRow (footerRow, fields);
+                       OnRowCreated (new GridViewRowEventArgs (footerRow));
+                       if (dataBinding) {
+                               footerRow.DataBind ();
+                               OnRowDataBound (new GridViewRowEventArgs (footerRow));
                        }
 
                        if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
                                bottomPagerRow = CreatePagerRow (fields.Length, dataSource);
                                table.Rows.Add (bottomPagerRow);
+                               OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
                        }
 
                        rows = new GridViewRowCollection (list);
-                       keys = new DataKeyArray (keyList);
-                       
-                       if (dataBinding)
-                               DataBind (false);
 
                        return dataSource.DataSourceCount;
                }
+
+               protected override Style CreateControlStyle ()
+               {
+                       TableStyle style = new TableStyle (ViewState);
+                       style.GridLines = GridLines.Both;
+                       style.CellSpacing = 0;
+                       return style;
+               }
                
                DataControlRowState GetRowState (int index)
                {
@@ -1208,7 +1314,8 @@ namespace System.Web.UI.WebControls
                protected virtual void InitializePager (GridViewRow row, int columnSpan, PagedDataSource dataSource)
                {
                        TableCell cell = new TableCell ();
-                       cell.ColumnSpan = columnSpan;
+                       if (columnSpan > 1)
+                               cell.ColumnSpan = columnSpan;
                        
                        if (pagerTemplate != null)
                                pagerTemplate.InstantiateIn (cell);
@@ -1239,16 +1346,16 @@ namespace System.Web.UI.WebControls
                        bool accessibleHeader = false;
 
                        switch (row.RowType) {
-                               case DataControlRowType.Header:
-                                       ctype = DataControlCellType.Header; 
-                                       accessibleHeader = UseAccessibleHeader;
-                                       break;
-                               case DataControlRowType.Footer:
-                                       ctype = DataControlCellType.Footer;
-                                       break;
-                               default:
-                                       ctype = DataControlCellType.DataCell;
-                                       break;
+                       case DataControlRowType.Header:
+                               ctype = DataControlCellType.Header; 
+                               accessibleHeader = UseAccessibleHeader;
+                               break;
+                       case DataControlRowType.Footer:
+                               ctype = DataControlCellType.Footer;
+                               break;
+                       default:
+                               ctype = DataControlCellType.DataCell;
+                               break;
                        }
                        
                        for (int n=0; n<fields.Length; n++) {
@@ -1312,31 +1419,90 @@ namespace System.Web.UI.WebControls
                
                public sealed override void DataBind ()
                {
-                       DataSourceView view = GetData ();
-                       if (AllowPaging && view.CanPage) {
-                               SelectArguments.StartRowIndex = PageIndex * PageSize;
-                               SelectArguments.MaximumRows = PageSize;
-                               if (view.CanRetrieveTotalRowCount)
-                                       SelectArguments.RetrieveTotalRowCount = true;
-                       }
-
-                       if (sortExpression != "") {
-                               if (sortDirection == SortDirection.Ascending)
-                                       SelectArguments.SortExpression = sortExpression;
-                               else
-                                       SelectArguments.SortExpression = sortExpression + " DESC";
-                       }
-                       
+                       DataKeyArrayList.Clear ();
                        cachedKeyProperties = null;
                        base.DataBind ();
+
+                       keys = new DataKeyArray (DataKeyArrayList);
                }
                
-               protected override void PerformDataBinding (IEnumerable data)
+               protected internal override void PerformDataBinding (IEnumerable data)
                {
                        base.PerformDataBinding (data);
                }
+
+               protected internal virtual void PrepareControlHierarchy ()
+               {
+                       if (table == null)
+                               return;
+                       
+                       table.Caption = Caption;
+                       table.CaptionAlign = CaptionAlign;
+                       
+                       foreach (GridViewRow row in table.Rows) {
+                               switch (row.RowType) {
+                               case DataControlRowType.Header:
+                                       if (headerStyle != null && !headerStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom(headerStyle);
+                                       row.Visible = ShowHeader;
+                                       break;
+                               case DataControlRowType.Footer:
+                                       if (footerStyle != null && !footerStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (footerStyle);
+                                       row.Visible = ShowFooter;
+                                       break;
+                               case DataControlRowType.Pager:
+                                       if (pagerStyle != null && !pagerStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (pagerStyle);
+                                       break;
+                               case DataControlRowType.EmptyDataRow:
+                                       if (emptyDataRowStyle != null && !emptyDataRowStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (emptyDataRowStyle);
+                                       break;
+                               case DataControlRowType.DataRow:
+                                       if (rowStyle != null && !rowStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (rowStyle);
+                                       if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null && !alternatingRowStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (alternatingRowStyle);
+                                       if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null && !selectedRowStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (selectedRowStyle);
+                                       if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null && !editRowStyle.IsEmpty)
+                                               row.ControlStyle.CopyFrom (editRowStyle);
+                                       break;
+                               default:
+                                       break;
+                               }
+
+                               foreach (TableCell cell in row.Cells) {
+                                       DataControlFieldCell fcell = cell as DataControlFieldCell;
+                                       if (fcell != null) {
+                                               DataControlField field = fcell.ContainingField;
+                                               switch (row.RowType) {
+                                               case DataControlRowType.Header:
+                                                       if (field.HeaderStyleCreated && !field.HeaderStyle.IsEmpty)
+                                                               cell.ControlStyle.CopyFrom (field.HeaderStyle);
+                                                       break;
+                                               case DataControlRowType.Footer:
+                                                       if (field.FooterStyleCreated && !field.FooterStyle.IsEmpty)
+                                                               cell.ControlStyle.CopyFrom (field.FooterStyle);
+                                                       break;
+                                               default:
+                                                       if (field.ControlStyleCreated && !field.ControlStyle.IsEmpty)
+                                                               foreach (Control c in cell.Controls) {
+                                                                       WebControl wc = c as WebControl;
+                                                                       if (wc != null)
+                                                                               wc.ControlStyle.MergeWith (field.ControlStyle);
+                                                               }
+                                                       if (field.ItemStyleCreated && !field.ItemStyle.IsEmpty)
+                                                               cell.ControlStyle.CopyFrom (field.ItemStyle);
+                                                       break;
+                                               }
+                                       }
+                               }
+                       }
+               }
                
-               protected override void OnInit (EventArgs e)
+               protected internal override void OnInit (EventArgs e)
                {
                        Page.RegisterRequiresControlState (this);
                        base.OnInit (e);
@@ -1364,11 +1530,23 @@ namespace System.Web.UI.WebControls
                        GridViewCommandEventArgs args = e as GridViewCommandEventArgs;
                        if (args != null) {
                                OnRowCommand (args);
-                               ProcessEvent (args.CommandName, args.CommandArgument as string);
+                               string param = args.CommandArgument as string;
+                               if (param == null || param.Length == 0) {
+                                       GridViewRow row = args.Row;
+                                       if (row != null)
+                                               param = row.RowIndex.ToString();
+                               }
+                               ProcessEvent (args.CommandName, param);
+                               return true;
                        }
                        return base.OnBubbleEvent (source, e);
                }
                
+               void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
+               {
+                       RaisePostBackEvent (eventArgument);
+               }
+
                // This is prolly obsolete
                protected virtual void RaisePostBackEvent (string eventArgument)
                {
@@ -1383,95 +1561,95 @@ namespace System.Web.UI.WebControls
                {
                        switch (eventName)
                        {
-                               case DataControlCommands.PageCommandName:
-                                       int newIndex = -1;
-                                       switch (param) {
-                                               case DataControlCommands.FirstPageCommandArgument:
-                                                       newIndex = 0;
-                                                       break;
-                                               case DataControlCommands.LastPageCommandArgument:
-                                                       newIndex = PageCount - 1;
-                                                       break;
-                                               case DataControlCommands.NextPageCommandArgument:
-                                                       if (PageIndex < PageCount - 1) newIndex = PageIndex + 1;
-                                                       break;
-                                               case DataControlCommands.PreviousPageCommandArgument:
-                                                       if (PageIndex > 0) newIndex = PageIndex - 1;
-                                                       break;
-                                               default:
-                                                       newIndex = int.Parse (param) - 1;
-                                                       break;
-                                       }
-                                       ShowPage (newIndex);
-                                       break;
-                                       
+                       case DataControlCommands.PageCommandName:
+                               int newIndex = -1;
+                               switch (param) {
                                case DataControlCommands.FirstPageCommandArgument:
-                                       ShowPage (0);
+                                       newIndex = 0;
                                        break;
-
                                case DataControlCommands.LastPageCommandArgument:
-                                       ShowPage (PageCount - 1);
+                                       newIndex = PageCount - 1;
                                        break;
-                                       
                                case DataControlCommands.NextPageCommandArgument:
-                                       if (PageIndex < PageCount - 1)
-                                               ShowPage (PageIndex + 1);
+                                       newIndex = PageIndex + 1;
                                        break;
-
                                case DataControlCommands.PreviousPageCommandArgument:
-                                       if (PageIndex > 0)
-                                               ShowPage (PageIndex - 1);
+                                       newIndex = PageIndex - 1;
                                        break;
-                                       
-                               case DataControlCommands.SelectCommandName:
-                                       SelectRow (int.Parse (param));
+                               default:
+                                       int paramIndex = 0;
+                                       int.TryParse (param, out paramIndex);
+                                       newIndex = paramIndex - 1;
                                        break;
+                               }
+                               ShowPage (newIndex);
+                               break;
                                        
-                               case DataControlCommands.EditCommandName:
-                                       EditRow (int.Parse (param));
-                                       break;
+                       case DataControlCommands.FirstPageCommandArgument:
+                               ShowPage (0);
+                               break;
+
+                       case DataControlCommands.LastPageCommandArgument:
+                               ShowPage (PageCount - 1);
+                               break;
                                        
-                               case DataControlCommands.UpdateCommandName:
-                                       UpdateRow (EditIndex, true);
-                                       break;
+                       case DataControlCommands.NextPageCommandArgument:
+                               if (PageIndex < PageCount - 1)
+                                       ShowPage (PageIndex + 1);
+                               break;
+
+                       case DataControlCommands.PreviousPageCommandArgument:
+                               if (PageIndex > 0)
+                                       ShowPage (PageIndex - 1);
+                               break;
                                        
-                               case DataControlCommands.CancelCommandName:
-                                       CancelEdit ();
-                                       break;
+                       case DataControlCommands.SelectCommandName:
+                               SelectRow (int.Parse (param));
+                               break;
                                        
-                               case DataControlCommands.DeleteCommandName:
-                                       DeleteRow (int.Parse (param));
-                                       break;
+                       case DataControlCommands.EditCommandName:
+                               EditRow (int.Parse (param));
+                               break;
                                        
-                               case DataControlCommands.SortCommandName:
-                                       Sort (param);
-                                       break;
+                       case DataControlCommands.UpdateCommandName:
+                               UpdateRow (EditIndex, true);
+                               break;
+                                       
+                       case DataControlCommands.CancelCommandName:
+                               CancelEdit ();
+                               break;
+                                       
+                       case DataControlCommands.DeleteCommandName:
+                               DeleteRow (int.Parse (param));
+                               break;
+                                       
+                       case DataControlCommands.SortCommandName:
+                               Sort (param);
+                               break;
                        }
                }
                
                void Sort (string newSortExpression)
                {
-                       SortDirection newDirection;
-                       if (sortExpression == newSortExpression) {
-                               if (sortDirection == SortDirection.Ascending)
-                                       newDirection = SortDirection.Descending;
-                               else
-                                       newDirection = SortDirection.Ascending;
-                       } else
-                               newDirection = sortDirection;
-                       
+                       SortDirection newDirection = SortDirection.Ascending;
+                       if (sortExpression == newSortExpression && sortDirection == SortDirection.Ascending)
+                               newDirection = SortDirection.Descending;
+
                        Sort (newSortExpression, newDirection);
                }
                
-               public void Sort (string newSortExpression, SortDirection newSortDirection)
+               public virtual void Sort (string newSortExpression, SortDirection newSortDirection)
                {
                        GridViewSortEventArgs args = new GridViewSortEventArgs (newSortExpression, newSortDirection);
                        OnSorting (args);
                        if (args.Cancel) return;
                        
-                       sortExpression = args.SortExpression;
-                       sortDirection = args.SortDirection;
-                       RequireBinding ();
+               if (IsBoundUsingDataSourceID) {
+                       EditIndex = -1;
+                       PageIndex = 0;
+                       SortExpression = args.SortExpression;
+                       SortDirection = args.SortDirection;
+               }
                        
                        OnSorted (EventArgs.Empty);
                }
@@ -1518,12 +1696,12 @@ namespace System.Web.UI.WebControls
                [MonoTODO ("Support two-way binding expressions")]
                public virtual void UpdateRow (int rowIndex, bool causesValidation)
                {
-                       if (causesValidation)
+                       if (causesValidation && Page != null)
                                Page.Validate ();
                        
                        if (rowIndex != EditIndex) throw new NotSupportedException ();
-                       
-                       currentEditOldValues = oldEditValues.Values;
+
+                       currentEditOldValues = OldEditValues.Values;
 
                        GridViewRow row = Rows [rowIndex];
                        currentEditRowKeys = DataKeys [rowIndex].Values;
@@ -1533,13 +1711,15 @@ namespace System.Web.UI.WebControls
                        OnRowUpdating (args);
                        if (!args.Cancel) {
                                DataSourceView view = GetData ();
-                               if (view == null) throw new HttpException ("The DataSourceView associated to data bound control was null");
-                               view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
+                               if (view == null)
+                                       throw new HttpException ("The DataSourceView associated to data bound control was null");
+                               if(view.CanUpdate)
+                                       view.Update (currentEditRowKeys, currentEditNewValues, currentEditOldValues, new DataSourceViewOperationCallback (UpdateCallback));
                        } else
                                EndRowEdit ();
                }
 
-        bool UpdateCallback (int recordsAffected, Exception exception)
+               bool UpdateCallback (int recordsAffected, Exception exception)
                {
                        GridViewUpdatedEventArgs dargs = new GridViewUpdatedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditOldValues, currentEditNewValues);
                        OnRowUpdated (dargs);
@@ -1550,7 +1730,7 @@ namespace System.Web.UI.WebControls
                        return dargs.ExceptionHandled;
                }
                
-               public void DeleteRow (int rowIndex)
+               public virtual void DeleteRow (int rowIndex)
                {
                        GridViewRow row = Rows [rowIndex];
                        currentEditRowKeys = DataKeys [rowIndex].Values;
@@ -1562,7 +1742,7 @@ namespace System.Web.UI.WebControls
                        if (!args.Cancel) {
                                RequireBinding ();
                                DataSourceView view = GetData ();
-                               if (view != null)
+                               if (view != null && view.CanDelete)
                                        view.Delete (currentEditRowKeys, currentEditNewValues, new DataSourceViewOperationCallback (DeleteCallback));
                                else {
                                        GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (0, null, currentEditRowKeys, currentEditNewValues);
@@ -1571,7 +1751,7 @@ namespace System.Web.UI.WebControls
                        }
                }
 
-        bool DeleteCallback (int recordsAffected, Exception exception)
+               bool DeleteCallback (int recordsAffected, Exception exception)
                {
                        GridViewDeletedEventArgs dargs = new GridViewDeletedEventArgs (recordsAffected, exception, currentEditRowKeys, currentEditNewValues);
                        OnRowDeleted (dargs);
@@ -1593,21 +1773,61 @@ namespace System.Web.UI.WebControls
                        object[] state = (object[]) ob;
                        base.LoadControlState (state[0]);
                        pageIndex = (int) state[1];
-                       pageCount = (int) state[2];
-                       selectedIndex = (int) state[3];
-                       editIndex = (int) state[4];
-                       sortExpression = (string) state[5];
-                       sortDirection = (SortDirection) state[6];
+                       selectedIndex = (int) state[2];
+                       editIndex = (int) state[3];
+                       sortExpression = (string) state[4];
+                       sortDirection = (SortDirection) state[5];
+                       DataKeyNames = (string []) state [6];
+                       if (state [7] != null)
+                               LoadDataKeyArrayState ((object []) state [7]);
+                       if (state [8] != null)
+                               ((IStateManager) OldEditValues).LoadViewState (state [8]);
                }
                
                protected internal override object SaveControlState ()
                {
+                       if (EnableSortingAndPagingCallbacks) {
+                               Page.ClientScript.RegisterHiddenField (ClientID + "_Page", PageIndex.ToString ());
+                               Page.ClientScript.RegisterHiddenField (ClientID + "_SortExpression", SortExpression);
+                               Page.ClientScript.RegisterHiddenField (ClientID + "_SortDirection", ((int)SortDirection).ToString());
+                       }
+
                        object bstate = base.SaveControlState ();
-                       return new object[] {
-                               bstate, pageIndex, pageCount, selectedIndex, editIndex, sortExpression, sortDirection
-                       };
+                       return new object [] {
+                               bstate, 
+                               pageIndex, 
+                               selectedIndex, 
+                               editIndex, 
+                               sortExpression, 
+                               sortDirection, 
+                               DataKeyNames,
+                               SaveDataKeyArrayState (),
+                               (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState ())
+                                       };
                }
-               
+
+               object [] SaveDataKeyArrayState ()
+               {
+                       if (keys == null)
+                               return null;
+
+                       object [] state = new object [keys.Count];
+                       for (int i = 0; i < keys.Count; i++) {
+                               state [i] = ((IStateManager) keys [i]).SaveViewState ();
+                       }
+                       return state;
+               }
+
+               void LoadDataKeyArrayState (object [] state)
+               {
+                       for (int i = 0; i < state.Length; i++) {
+                               DataKey dataKey = new DataKey (new OrderedDictionary (DataKeyNames.Length), DataKeyNames);
+                               ((IStateManager) dataKey).LoadViewState (state [i]);
+                               DataKeyArrayList.Add (dataKey);
+                       }
+                       keys = new DataKeyArray (DataKeyArrayList);
+               }
+
                protected override void TrackViewState()
                {
                        base.TrackViewState();
@@ -1630,7 +1850,7 @@ namespace System.Web.UI.WebControls
 
                protected override object SaveViewState()
                {
-                       object[] states = new object [14];
+                       object[] states = new object [12];
                        states[0] = base.SaveViewState();
                        states[1] = (columns == null ? null : ((IStateManager)columns).SaveViewState());
                        states[2] = (pagerSettings == null ? null : ((IStateManager)pagerSettings).SaveViewState());
@@ -1642,8 +1862,6 @@ namespace System.Web.UI.WebControls
                        states[8] = (selectedRowStyle == null ? null : ((IStateManager)selectedRowStyle).SaveViewState());
                        states[9] = (editRowStyle == null ? null : ((IStateManager)editRowStyle).SaveViewState());
                        states[10] = (emptyDataRowStyle == null ? null : ((IStateManager)emptyDataRowStyle).SaveViewState());
-                       states[11] = (keys == null ? null : ((IStateManager)keys).SaveViewState());
-                       states[12] = (oldEditValues == null ? null : ((IStateManager)oldEditValues).SaveViewState());
                        
                        if (autoFieldProperties != null) {
                                object[] data = new object [autoFieldProperties.Length];
@@ -1652,7 +1870,7 @@ namespace System.Web.UI.WebControls
                                        data [n] = ((IStateManager)autoFieldProperties [n]).SaveViewState ();
                                        if (data [n] != null) allNull = false;
                                }
-                               if (!allNull) states [13] = data;
+                               if (!allNull) states [11] = data;
                        }
 
                        for (int i = states.Length - 1; i >= 0; i--) {
@@ -1672,8 +1890,8 @@ namespace System.Web.UI.WebControls
 
                        object [] states = (object []) savedState;
                        
-                       if (states[13] != null) {
-                               object[] data = (object[]) states [13];
+                       if (states[11] != null) {
+                               object[] data = (object[]) states [11];
                                autoFieldProperties = new AutoGeneratedFieldProperties [data.Length];
                                for (int n=0; n<data.Length; n++) {
                                        IStateManager p = new AutoGeneratedFieldProperties ();
@@ -1684,7 +1902,6 @@ namespace System.Web.UI.WebControls
                        }
 
                        base.LoadViewState (states[0]);
-                       EnsureChildControls ();
                        
                        if (states[1] != null) ((IStateManager)Columns).LoadViewState (states[1]);
                        if (states[2] != null) ((IStateManager)PagerSettings).LoadViewState (states[2]);
@@ -1696,34 +1913,41 @@ namespace System.Web.UI.WebControls
                        if (states[8] != null) ((IStateManager)SelectedRowStyle).LoadViewState (states[8]);
                        if (states[9] != null) ((IStateManager)EditRowStyle).LoadViewState (states[9]);
                        if (states[10] != null) ((IStateManager)EmptyDataRowStyle).LoadViewState (states[10]);
-                       if (states[11] != null) ((IStateManager)DataKeys).LoadViewState (states[11]);
-                       if (states[12] != null && oldEditValues != null) ((IStateManager)oldEditValues).LoadViewState (states[12]);
                }
                
-               string ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
+               void ICallbackEventHandler.RaiseCallbackEvent (string eventArgs)
                {
-                       return RaiseCallbackEvent (eventArgs);
+                       RaiseCallbackEvent (eventArgs);
                }
                
-               protected virtual string RaiseCallbackEvent (string eventArgs)
+               protected virtual void RaiseCallbackEvent (string eventArgs)
                {
                        string[] clientData = eventArgs.Split ('|');
-                       pageIndex = int.Parse (clientData[0]);
-                       sortExpression = HttpUtility.UrlDecode (clientData[1]);
-                       if (sortExpression == "") sortExpression = null;
-                       RequireBinding ();
+                       PageIndex = int.Parse (clientData[0]);
+                       SortExpression = HttpUtility.UrlDecode (clientData [1]);
+                       SortDirection = (SortDirection) int.Parse (clientData [2]);
                        
-                       RaisePostBackEvent (clientData[2]);
-                       EnsureDataBound ();
+                       RaisePostBackEvent (clientData[3]);
+                       DataBind ();
+               }
+               
+               string ICallbackEventHandler.GetCallbackResult ()
+               {
+                       return GetCallbackResult ();
+               }
+
+               protected virtual string GetCallbackResult ()
+               {
+                       PrepareControlHierarchy ();
                        
                        StringWriter sw = new StringWriter ();
-                       sw.Write (PageIndex.ToString() + '|' + SortExpression + '|');
+                       sw.Write (PageIndex.ToString () + '|' + SortExpression + '|' + (int) SortDirection + '|');
 
                        HtmlTextWriter writer = new HtmlTextWriter (sw);
                        RenderGrid (writer);
                        return sw.ToString ();
                }
-               
+
                string ICallbackContainer.GetCallbackScript (IButtonControl control, string argument)
                {
                        return GetCallbackScript (control, argument);
@@ -1737,7 +1961,22 @@ namespace System.Web.UI.WebControls
                                return null;
                }
                
-               protected override void OnPreRender (EventArgs e)
+               protected override void OnPagePreLoad (object sender, EventArgs e)
+               {
+                       base.OnPagePreLoad (sender, e);
+
+                       if (Page.IsPostBack && EnableSortingAndPagingCallbacks) {
+                               int page;
+                               if (int.TryParse (Page.Request.Form [ClientID + "_Page"], out page))
+                                       PageIndex = page;
+                               int dir;
+                               if (int.TryParse (Page.Request.Form [ClientID + "_SortDirection"], out dir))
+                                       SortDirection = (SortDirection) dir;
+                               SortExpression = Page.Request.Form [ClientID + "_SortExpression"];
+                       }
+               }
+               
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
                        
@@ -1752,96 +1991,50 @@ namespace System.Web.UI.WebControls
                                string script = string.Format ("var {0} = new Object ();\n", cgrid);
                                script += string.Format ("{0}.pageIndex = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (PageIndex));
                                script += string.Format ("{0}.sortExp = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (SortExpression == null ? "" : SortExpression));
+                               script += string.Format ("{0}.sortDir = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral ((int) SortDirection));
                                script += string.Format ("{0}.uid = {1};\n", cgrid, ClientScriptManager.GetScriptLiteral (UniqueID));
                                Page.ClientScript.RegisterStartupScript (typeof(TreeView), this.UniqueID, script, true);
                                
                                // Make sure the basic script infrastructure is rendered
-                       Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
+                               Page.ClientScript.GetCallbackEventReference (this, "null", "", "null");
                                Page.ClientScript.GetPostBackClientHyperlink (this, "");
                        }
                }
-               
-               protected override void Render (HtmlTextWriter writer)
+
+               protected internal override void Render (HtmlTextWriter writer)
                {
+                       PrepareControlHierarchy ();
+
                        if (EnableSortingAndPagingCallbacks)
-                               base.RenderBeginTag (writer);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID);
+                       writer.RenderBeginTag (HtmlTextWriterTag.Div);
 
                        RenderGrid (writer);
-                       
-                       if (EnableSortingAndPagingCallbacks)
-                               base.RenderEndTag (writer);
+
+                       writer.RenderEndTag ();
                }
                
                void RenderGrid (HtmlTextWriter writer)
                {
-                       switch (GridLines) {
-                               case GridLines.Horizontal:
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Rules, "rows");
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
-                                       break;
-                               case GridLines.Vertical:
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Rules, "cols");
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
-                                       break;
-                               case GridLines.Both:
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Rules, "all");
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Border, "1");
-                                       break;
-                               default:
-                                       writer.AddAttribute (HtmlTextWriterAttribute.Border, "0");
-                                       break;
-                       }
+                       if (table == null)
+                               return;
+
+                       table.Render (writer);
+               }
+
+               PostBackOptions IPostBackContainer.GetPostBackOptions (IButtonControl control)
+               {
+                       if (control == null)
+                               throw new ArgumentNullException ("control");
                        
-                       writer.AddAttribute (HtmlTextWriterAttribute.Cellspacing, "0");
-                       writer.AddStyleAttribute (HtmlTextWriterStyle.BorderCollapse, "collapse");
-                       table.RenderBeginTag (writer);
+                       if (control.CausesValidation)
+                               throw new InvalidOperationException ("A button that causes validation in GridView '" + 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.");
                        
-                       foreach (GridViewRow row in table.Rows)
-                       {
-                               switch (row.RowType) {
-                                       case DataControlRowType.Header:
-                                               if (headerStyle != null)headerStyle.AddAttributesToRender (writer, row);
-                                               break;
-                                       case DataControlRowType.Footer:
-                                               if (footerStyle != null) footerStyle.AddAttributesToRender (writer, row);
-                                               break;
-                                       case DataControlRowType.Pager:
-                                               if (pagerStyle != null) pagerStyle.AddAttributesToRender (writer, row);
-                                               break;
-                                       case DataControlRowType.EmptyDataRow:
-                                               if (emptyDataRowStyle != null) emptyDataRowStyle.AddAttributesToRender (writer, row);
-                                               break;
-                                       default:
-                                               if (rowStyle != null) rowStyle.AddAttributesToRender (writer, row);
-                                               break;
-                               }
+                       PostBackOptions options = new PostBackOptions (this);
+                       options.Argument = control.CommandName + "$" + control.CommandArgument;
+                       options.RequiresJavaScriptProtocol = true;
 
-                               if ((row.RowState & DataControlRowState.Alternate) != 0 && alternatingRowStyle != null)
-                                       alternatingRowStyle.AddAttributesToRender (writer, row);
-                               if ((row.RowState & DataControlRowState.Edit) != 0 && editRowStyle != null)
-                                       editRowStyle.AddAttributesToRender (writer, row);
-                               if ((row.RowState & DataControlRowState.Selected) != 0 && selectedRowStyle != null)
-                                       selectedRowStyle.AddAttributesToRender (writer, row);
-                               
-                               row.RenderBeginTag (writer);
-                               
-                               foreach (TableCell cell in row.Cells) {
-                                       DataControlFieldCell fcell = cell as DataControlFieldCell;
-                                       if (fcell != null) {
-                                               Style cellStyle = null;
-                                               switch (row.RowType) {
-                                                       case DataControlRowType.Header: cellStyle = fcell.ContainingField.HeaderStyle; break;
-                                                       case DataControlRowType.Footer: cellStyle = fcell.ContainingField.FooterStyle; break;
-                                                       default: cellStyle = fcell.ContainingField.ItemStyle; break;
-                                               }
-                                               if (cellStyle != null)
-                                                       cellStyle.AddAttributesToRender (writer, cell);
-                                       }
-                                       cell.Render (writer);
-                               }
-                               row.RenderEndTag (writer);
-                       }
-                       table.RenderEndTag (writer);
+                       return options;
                }
        }
 }