2
votes

I am having a User control [ascx] which is a radgrid. It also has a Edit column template which allow user to Insert/ change/update the values.

I am loading this user control on click of a button [Say EDIT] in aspx page.

When I click on EDIT button of aspx page the user control loads perfectly, but when I click on the Add New Record of user control I get this error message.

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.

//code of user control -ascx

<telerik:RadGrid AllowAutomaticDeletes="True"
    AllowAutomaticInserts="False" AllowAutomaticUpdates="False"
    Height="410px" ID="rgrd1" runat="server" AutoGenerateColumns="False"
    OnUpdateCommand="rgrd1_UpdateCommand"
    OnInsertCommand="rgrd1_InsertCommand"  OnNeedDataSource="rgrd1_NeedDataSource" GridLines="None">

    <MasterTableView CommandItemDisplay="top" CommandItemStyle-Wrap="False" CommandItemStyle-HorizontalAlign="Left"
        DataKeyNames="Type">
        <Columns>
            <telerik:GridEditCommandColumn UniqueName="EditColumn" HeaderStyle-HorizontalAlign="left"
                HeaderText="Edit" ButtonType="ImageButton">
            </telerik:GridEditCommandColumn>
            <telerik:GridTemplateColumn DataField="Type" HeaderStyle-HorizontalAlign="left"
                HeaderText="Type" UniqueName="Type">
                <ItemTemplate>
                    <asp:Label ID="TypeLabel" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
                </ItemTemplate>
            </telerik:GridTemplateColumn>

        </Columns>
        <EditFormSettings EditFormType="Template">
            <EditColumn FilterControlAltText="Filter EditCommandColumn1 column" UniqueName="EditCommandColumn1">
            </EditColumn>
            <FormTemplate>
                <table>
                        <td>
                            <telerik:RadTextBox ID="txtType" Width="50" runat="server"  Text='<%# Eval("Type") %>'>
                            </telerik:RadTextBox>

                        </td>
                    </tr>
                </table>
            </FormTemplate>
        </EditFormSettings>

    </MasterTableView>
    <HeaderStyle HorizontalAlign="Center" />
</telerik:RadGrid>

..................................... Code of my aspx page - in which i am loading the above usercontrol in Radwindow

On click of EDIT button - below code i have written-

RadWindow window = new RadWindow();
window.Height = Unit.Pixel(500);
window.Width = Unit.Pixel(500);
window.VisibleOnPageLoad = true;
UserControl uc = (UserControl)Page.LoadControl("../../Controls/TypeUserControl.ascx");
uc.EnableViewState = false;
window.ContentContainer.Controls.Add(uc);
pnl.Controls.Add(window);

When I click on Add New Record in usercontrol it throws the exception "Failed to load view state:"

I have aspx page on which this user control is loaded is being inherited by my BasePage.

Exception is coming in OnPreRender of base page

protected override void OnPreRender(EventArgs e)
{
    try
    {
         base.OnPreRender(e);
    }
}

User control - code behing

    public partial class TypeUserControl : System.Web.UI.UserControl
{

    protected void rgrd1Types_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    {
        try
        {
           //dbase call
        }
        catch (Exception ex)
        {
            SetValidationMessage(ex.Message.ToString());
        }
    }

    protected void rgrd1_InsertCommand(object source, GridCommandEventArgs e)
    {
        try
        {
            //dbase call

        }
        catch (Exception ex)
        {
            SetValidationMessage(ex.Message.ToString());
        }
    }
3
which line is throwing the error..?what if you remove the path and just have the following UserControl uc = (UserControl)Page.LoadControl("TypeUserControl.ascx"); - MethodMan
exception is coming on PreRender event of Base page - New Coder
please read the following answer located here.. looks like you may not need that call stackoverflow.com/questions/18984242/… - MethodMan
the problem is -the project is existing one - and i cannot change the BasePage...any other option pls - New Coder
will you please provide the code behind for the User Control? - Malachi

3 Answers

0
votes

I don't know if this is the issue, but your HTML is not correct in your Form Template

                    <table>

                            <td>
                                <telerik:RadTextBox ID="txtType" Width="50" runat="server"  Text='<%# Eval("Type") %>'>
                                </telerik:RadTextBox>

                            </td>
                        </tr>

                    </table>

you are missing the opening <tr> tag. this could have something to do with the issue.

you should double check all your code to make sure that it is correct.

--

I am also guessing that you should remove this line of code from the Edit button's OnClick() event

    uc.EnableViewState = false;
0
votes

You have to recreate the control on postback as you add it dynamically. Recreate or Add the control in the Init_page Eventhandler, there you can check the type of event or control, that caused the postback, to know that you should recreate this control. Can you post the code-behind file.

EDIT: It's a long time ago, when I did this. But here is a working example. I think there is a better way. Check the keys collection, which button caused the postback, if it is a certain button in your ascx control then readd your control to the page or whereever you put it, but it must be the same place on postback, otherwise you will get an error, I think.

protected override void OnInit(EventArgs e) { base.OnInit(e);

      if (this.Page.IsPostBack)           {
          var x = base.DeterminePostBackMode();

          if (x.Keys.Get(3).Contains("btnInControl"))
          {
              Control ctrl = Page.LoadControl("WebUserControl1.ascx");
              this.Page.Form.Controls.Add(ctrl);
          }       
} 
}
0
votes

It has been a year since you posted this issue but just in case someone still facing this: here is the main root of this type of error. I have been struggling big time with it.

  • The easiest way to fix your bug is to set to the control you add dynamically :

    EnableViewState = false
    
  • If you need the Viewstate, the other options you have are to add the control you add dynamically onInit, or recreate it on every Postback.

Hope it helps.

See Funkylife's comment for more information.