Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Failed to load viewstate on dynamic user controls?

Posted on 2009-05-05
8
Medium Priority
?
1,531 Views
Last Modified: 2013-12-17
Hi,
Basically, i can add a photomedia control and youtube control by clicking on respective add buttons. My dynamic user controls can be added successfully EXCEPT for this combination.

youtube - > youtube -> photomedia -> then error when a new user control added!!!
youtube -> photomedia -> youtube -> i can add any other user control. No issue here

If you look at the code below, these 3 controls are added when the first time the page init. Again, if the arrangment is changed other than the arragement above, then i'm able to add a new user control with no issue.

Any help is greatly appreciated.

PS: Been tight down by this issue for the last few weeks...still struggling to resolve it but to no avail :(

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.
Imports System.Data
Imports System.IO                           'Contains File.Delete() method and FileInfo type for delete purpose.
 
'Google Gdata API namespaces
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.GData.YouTube
 
Partial Class MyAccount_Debug
    Inherits System.Web.UI.Page
 
    'List to keep track of dynamically added user controls.
    Protected Property ctrls() As List(Of String)
        Get
            If Session("ctrls") Is Nothing Then
                Session("ctrls") = New List(Of String)
            End If
            Return CType(Session("ctrls"), List(Of String))
        End Get
        Set(ByVal value As List(Of String))
            Session("ctrls") = value
        End Set
    End Property
 
    'Add new Youtube Modules
    Protected Sub btnAddYoutube_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddYoutube.Click
 
        Dim Youtube As Youtube = LoadControl("~/UserControl/Youtube.ascx")
        Youtube.ID = "Youtube" & Session("ctrl_id_increment")
 
        'Concat both identifier and ID, will be splitted during page load.
        ctrls.Add(String.Format("{0}|{1}", "Youtube", Session("ctrl_id_increment")))
 
        'Lastly, increment for next control ID
        Session("ctrl_id_increment") += 1
 
        PlaceHolder1.Controls.Add(Youtube)
        PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
 
    End Sub
 
    'Add new Photo Media
    Protected Sub btnAddPhotoMedia_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddPhotoMedia.Click
 
        Dim PhotoMedia As PhotoMedia = LoadControl("~/UserControl/PhotoMedia.ascx")
        PhotoMedia.ID = "PhotoMedia" & Session("ctrl_id_increment")
 
        'Finally add the controls to the string list.
        ctrls.Add(String.Format("{0}|{1}", "PhotoMedia", Session("ctrl_id_increment")))
 
        'Finally, increment for next control ID
        Session("ctrl_id_increment") += 1
 
        PlaceHolder1.Controls.Add(PhotoMedia)
        PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
 
    End Sub
 
    'Init routine. This will kick off prior to the page_load
    Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        If Not Page.IsPostBack Then
 
            'Initiate the list class
            ctrls = New List(Of String)
 
            '#######YOUTUBE 1###############
            Dim Youtube As Youtube = LoadControl("~/UserControl/Youtube.ascx")
            Youtube.ID = "Youtube1" 'txtType.Text & txtControlID.Text
            ctrls.Add(String.Format("{0}|{1}", "Youtube", "1"))
 
            '#######YOUTUBE 2###############
            Dim Youtube2 As Youtube = LoadControl("~/UserControl/Youtube.ascx")
            Youtube2.ID = "Youtube3" 'txtType.Text & txtControlID.Text
            ctrls.Add(String.Format("{0}|{1}", "Youtube", "2"))
 
            '##########PHOTO MEDIA###############
            '2) Initialize the user control and assign control ID
            Dim PhotoMedia As PhotoMedia = LoadControl("~/UserControl/PhotoMedia.ascx")
            PhotoMedia.ID = "PhotoMedia2" ' txtType.Text & txtControlID.Text
            ctrls.Add(String.Format("{0}|{1}", "PhotoMedia", "3"))
 
            'Now add the users controls to the placeholder.
            'Problem seen, when arragement in youtube-youtube-photomedia!
            PlaceHolder1.Controls.Add(Youtube)
            PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
            PlaceHolder1.Controls.Add(Youtube2)
            PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
            PlaceHolder1.Controls.Add(PhotoMedia)
            PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
 
            'Next added control will take ID of 4
            Session("ctrl_id_increment") = 4
 
        Else
 
            'Renumerate the list, and add in all the objects (usercontrol, lateral control) to the page's placeholder.
            For Each ctrl As String In ctrls
                Dim c As String() = ctrl.Split("|")
                Select Case c(0)
                    Case "Youtube"
                        Dim Youtube As Youtube = LoadControl("~/UserControl/Youtube.ascx")
                        Youtube.ID = String.Concat(c(0).ToString, c(1).ToString)
                        PlaceHolder1.Controls.Add(Youtube)
 
                    Case "PhotoMedia"
                        Dim PhotoMedia As PhotoMedia = LoadControl("~/UserControl/PhotoMedia.ascx")
                        PhotoMedia.ID = String.Concat(c(0).ToString, c(1).ToString)
                        PlaceHolder1.Controls.Add(PhotoMedia)
 
                End Select
            Next
 
        End If
 
        MyBase.OnInit(e)
 
    End Sub
 
End Class

Open in new window

0
Comment
Question by:tangteng78
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 29

Accepted Solution

by:
David H.H.Lee earned 1500 total points
ID: 24311729
Hi tangteng78,
It seem like the duplication dynamic control creation. Try verify it under your specified specifications under required circumtance/event. You can add some logic to check the duplication before dynamic control creation in all the involved.
eg:

'Add new Youtube Modules
    Protected Sub btnAddYoutube_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddYoutube.Click
 
        'check object existance
        Dim obj As Control = FindControl("Youtube" & Session("ctrl_id_increment"))
 
        If obj Is Nothing Then

        Dim Youtube As Youtube = LoadControl("~/UserControl/Youtube.ascx")
        Youtube.ID = "Youtube" & Session("ctrl_id_increment")
 
        'Concat both identifier and ID, will be splitted during page load.
        ctrls.Add(String.Format("{0}|{1}", "Youtube", Session("ctrl_id_increment")))
 
        'Lastly, increment for next control ID
        Session("ctrl_id_increment") += 1
 
        PlaceHolder1.Controls.Add(Youtube)
        PlaceHolder1.Controls.Add(New LiteralControl("<br />"))

        End If    
    End Sub
 
0
 

Author Comment

by:tangteng78
ID: 24312165
x_com,
i use the debug to trace every steps of the codes...and it seems that the error doesn't occur during the on_click event, BUT only after the on_init event.
PS: It doesn't even hit the on_click event yet.
            'Renumerate the list, and add in all the objects (usercontrol, lateral control) to the page's placeholder.
            For Each ctrl As String In ctrls
                Dim c As String() = ctrl.Split("|")
                Select Case c(0)
                    Case "Youtube"
                        Dim Youtube As Youtube = LoadControl("~/UserControl/Youtube.ascx")
                        Youtube.ID = String.Concat(c(0).ToString, c(1).ToString)
                        PlaceHolder1.Controls.Add(Youtube)

                    Case "PhotoMedia"
                        Dim PhotoMedia As PhotoMedia = LoadControl("~/UserControl/PhotoMedia.ascx")
                        PhotoMedia.ID = String.Concat(c(0).ToString, c(1).ToString)
                        PlaceHolder1.Controls.Add(PhotoMedia)

                End Select
            Next
 
 
0
 

Author Comment

by:tangteng78
ID: 24315147
Since the error happens on the photomedia user control, i started to strip down the user control by removing 3 textboxes (it has 1 fileupload, 4 textboxes and 4 buttons), and it works.

Not only that, basically stripping down the user control (doesn't matter what web control is taken out), it's able to solve the problem.

Any idea why is that?

I'm really baffled now
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24322103
Hi tangteng78,
>Since the error happens on the photomedia user control, i started to strip down the user control by removing 3 textboxes (it has 1 fileupload, 4 textboxes and 4 buttons), and it works.
May i see the code snippet that resides inside photomedia user control for further inspection? I'm curious if any restrictions that used there.
0
 

Author Comment

by:tangteng78
ID: 24322374
Not sure if my hypothesis is correct, but having the <img> server control screws up the whole dynamic thingy. I suspect it could be due to the postback/viewstate feature that this server control could NOT support. The same goes to the <label> server control.

Everytime i have these 2 server controls in my user control, something weird is going to happen.

Thus, i remove these 2 server controls (remain the textboxes) from the user control and i use the control state (of the user control property)  to persist the information that i want to retain on postback, and display it by calling the user_control.property rather than using <img> or <label>

That resolve my problem.

Any comments?
0
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24322529
Hi tangteng78,
>>..Everytime i have these 2 server controls in my user control, something weird is going to happen.
If the <label> or <image> control that invoked is declared properly, i don't see any reason why it not working. Perhaps you have to re-check if the postback or viewstate feature is calling properly instead. Post your design code and code-behind for these if you need any further assistance.

0
 

Author Comment

by:tangteng78
ID: 24323081
Thanks X-com, think I would go with my findings at the moment :)
0
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24323091
No problem :)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question