This is a migrated thread and some comments may be shown as answers.
failed to load viewstate
2 Answers 126 Views
This is a migrated thread and some comments may be shown as answers.
Michael
Top achievements
Rank 1
Michael asked on 26 Mar 2010, 05:13 PM
I'm getting the following error and I can' track down the reason.  I have a screen where the user selects criteria. I build the query behind the scenes for the onneeddatasource event  when they click search. On initial load I just display a dummy grid. When I click on search the page postback, assembles and runs the query and returns the correct grid as  expected.  If I click on search a second time or peform any type of post back I get the Failed to load viewstate.

Hopefully you can help me solve this mystery.  Thanks

Error:
Server Error in '/AARates' Application.  
--------------------------------------------------------------------------------  
 
Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.   
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.   
 
Exception Details: System.Web.HttpException: Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.  
 
Source Error:   
 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.    
 
Stack Trace:   
 
 
[HttpException (0x80004005): Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.]  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +306  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Control.LoadChildViewStateByIndex(ArrayList childState) +134  
   System.Web.UI.Control.LoadViewStateRecursive(Object savedState) +221  
   System.Web.UI.Page.LoadAllState() +312  
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1661  
 
   
 

Aspx Grid:
            <telerik:RadPane ID="gridPane" runat="server" Height="400px" Scrolling="None" OnClientResized="ClientResized" > 
                <telerik:RadGrid ID="ARGrid1" runat="server" Width="97%" Height="95%" GridLines="None" PageSize="40" 
                     AllowSorting="true" AllowPaging="true" Visible="true" OnNeedDataSource="ARGrid1_NeedDataSource" OnItemCreated="ARGrid1_ItemCreated" 
                     OnItemCommand="ARGrid1_ItemCommand" ShowStatusBar="true" ShowGroupPanel="true" Skin="Outlook">  
                     <MasterTableView AllowFilteringByColumn="true" AllowMultiColumnSorting="true" Width="100%" CommandItemDisplay="Top" AutoGenerateColumns="true">  
                        <HeaderStyle Width="200px" /> 
                        <Columns></Columns>  
                        <CommandItemSettings AddNewRecordText="" ShowExportToPdfButton="true" ShowExportToWordButton="true" ShowExportToExcelButton="true" ShowExportToCsvButton="true" /> 
                     </MasterTableView> 
                     <ClientSettings AllowColumnsReorder="true" AllowDragToGroup="true" ColumnsReorderMethod="Reorder" EnableRowHoverStyle="true">  
                        <Scrolling AllowScroll="true" UseStaticHeaders="true" SaveScrollPosition="false" FrozenColumnsCount="1" ScrollHeight="100%" /> 
                        <Resizing ClipCellContentOnResize="false" AllowColumnResize="true" /> 
                     </ClientSettings> 
                     <GroupingSettings ShowUnGroupButton="true" /> 
                     <ExportSettings IgnorePaging="true" OpenInNewWindow="true">  
                        <Pdf AllowPrinting="true" /> 
                     </ExportSettings> 
                </telerik:RadGrid> 
            </telerik:RadPane> 

Code Behind:
        protected void btnSearch_Click(object sender, EventArgs e)  
        {  
            bool pageerrors = false;  
 
            //Clear any existing messages  
            PgMessage.ClearMessages();  
 
            //Run validation before running report  
            //Check date rage  
            if (rdpbegin.SelectedDate == null || rdpend.SelectedDate == null)  
            {  
                PgMessage.DisplayMessage(PageMessage.MessageType.Warning, "* Invalid dates. Date range must be input");  
                pageerrors = true;  
            }  
            if (rdpbegin.SelectedDate > rdpend.SelectedDate)  
            {  
                PgMessage.DisplayMessage(PageMessage.MessageType.Warning, "* Date range is not valid");  
                pageerrors = true;  
            }  
 
            //Check List Type  
            if (rcbListType.SelectedIndex == 0)  
            {  
                PgMessage.DisplayMessage(PageMessage.MessageType.Warning, "* List type must be selected");  
                pageerrors = true;  
            }  
 
            //Ensure at least one code is in rlbCodes  
            if (rlbCodes.Items.Count == 0)  
            {  
                PgMessage.DisplayMessage(PageMessage.MessageType.Warning, "* At least one code must be entered");  
                pageerrors = true;  
            }  
 
            //Run report if no page errors  
            if (!pageerrors)   
            {   
                 
                 //ARGrid1.Visible = true;  
                ARGrid1.Rebind();  
 
                lnkbtnSave.Enabled = true;  
                lnkbtnSaveAs.Enabled = true;  
            }  
        }  
 
        private DataSet BuildRptQuery()  
        {  
            bool pullDaily = true;  
            string strquery = string.Empty;  
            DataSet AADataRpt;  
             
 
//            last = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1);   
 
            //Get dates  
            if (rdpbegin.SelectedDate != null)  
            {  
                DateTime begindt = new DateTime(rdpbegin.SelectedDate.Value.Year, rdpbegin.SelectedDate.Value.Month, 1);  
 
                if (begindt <= DateTime.Today.AddDays(-90))  
                {  
                    pullDaily = false;  
                    intbegindt = rdpbegin.SelectedDate.Value.Year * 100 + rdpbegin.SelectedDate.Value.Month;  
                    intenddt = rdpend.SelectedDate.Value.Year * 100 + rdpend.SelectedDate.Value.Month;  
                }  
                else  
                {  
                    strbegindt = rdpbegin.SelectedDate.ToString();  
                    strenddt = rdpend.SelectedDate.ToString();  
                }  
 
 
                //Get field name to search code list on  
                UserListType ult = UserListType.getByKey(Convert.ToInt16(rcbListType.SelectedValue));  
 
                switch (ult.Code)  
                {  
                    case "MBUS":  
                        codetype = "MbuCode";  
                        break;  
                    case "BOB":  
                        codetype = "BookOfBusiness";  
                        break;  
                    case "LOB":  
                        codetype = "LineOfBusiness";  
                        break;  
                    case "MBU":  
                        codetype = "MbuCode";  
                        break;  
                    case "CASE":  
                        codetype = "CaseCode";  
                        break;  
                    case "CONTR":  
                        codetype = "ContractCode";  
                        break;  
                }  
 
                codelist = BuildCodeListQuery();  
 
                //Get fields to return from the grid  
                fieldlist = string.Empty;  
                IList<RadListBoxItem> collection = rlbFields.CheckedItems;  
                foreach (RadListBoxItem item in collection)  
                {  
 
 
                    if (!pullDaily)  
                    {  
                        switch (item.Value)  
                        {  
                            case "ProductionDate":  
                                fieldlistfieldlist = fieldlist + "YearMo " + " [" + item.Text + "],";  
                                break;  
 
                            case "AADataAuditID":  
                                fieldlistfieldlist = fieldlist + "0" + " [" + item.Text + "],";  
                                break;  
                            default:  
                                fieldlistfieldlist = fieldlist + item.Value + " [" + item.Text + "],";  
                                break;  
                        }  
 
                    }  
                    else  
                    {  
                        fieldlistfieldlist = fieldlist + item.Value + " [" + item.Text + "],";  
                    }  
                }  
                fieldlistfieldlist = fieldlist.TrimEnd(',');  
 
 
                //Set report query  
                if (pullDaily)  
                {  
                    strquery = "Select " + fieldlist + " from AAData where ProductionDate >= '" + strbegindt + "' AND ";  
                    strquerystrquery = strquery + "ProductionDate <= '" + strenddt + "' AND " + codetype + " IN (" + codelist + ")";  
                    AADataAADataRpt = AAData.getAAReport(strquery);  
                }  
                else  
                {  
                    strquery = "Select " + fieldlist + " from AADataMonthly where YearMo >= " + intbegindt + " AND ";  
                    strquerystrquery = strquery + "YearMo <= " + intenddt + " AND " + codetype + " IN (" + codelist + ")";  
                    AADataRpt = AADataMonthly.getAAReport(strquery);  
                }  
 
                Session["itemsCount"] = AADataRpt.Tables[0].Rows.Count;  // myDataTable.DefaultView.Count;  
            }  
            else  
            {  
                AADataAADataRpt = AAData.getAAReport("Select ProductionDate,CaseCode,ContractCode,MbuCode from AAData where ProductionDate = 01/01/1900");  
            }  
            return AADataRpt;  
 
        }  
 
        protected void ARGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)  
        {  
            ARGrid1.DataSource = BuildRptQuery();   
        } 

2 Answers, 1 is accepted

Sort by
0
Accepted
Stacy
Top achievements
Rank 1
answered on 26 Mar 2010, 05:43 PM
Hey Michael,

I have rec'd that error before when the settings for my radGrid don't match up with the data in the ViewState.  I build all of my columns and RadGrid properties at run-time to support multiple report definitions.  It looks like you are doing the same.

e.g. If you have a report with let's say 5 columns and then the user changed something, I PostBack and then I would change the configuration of my RadGrid in the Page_Init to 3 columns (let's say) and the ViewState from 5-columns != 3-Columns.  Know what I mean?  I hope this makes sense and is beneficial.

http://www.telerik.com/help/aspnet-ajax/grid-changing-structure-dynamically.html

Stacy
0
Michael
Top achievements
Rank 1
answered on 26 Mar 2010, 06:18 PM
Yes, that does make sense and was beneficial. I now need to figure out the best way to rework my code in order to handle the changes needed to avoid this error.  Thank you.
Tags
Grid
Asked by
Michael
Top achievements
Rank 1
Answers by
Stacy
Top achievements
Rank 1
Michael
Top achievements
Rank 1
Share this question
or