Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net: User controls added to placeholder dynamically cannot retrieve values

I am adding some user controls dynamically to a PlaceHolder server control. My user control consists of some labels and some textbox controls.

When I submit the form and try to view the contents of the textboxes (within each user control) on the server, they are empty.

When the postback completes, the textboxes have the data that I entered prior to postback. This tells me that the text in the boxes are being retained through ViewState. I just don't know why I can't find them when I'm debugging.

Can someone please tell me why I would not be seeing the data the user entered on the server?

Thanks for any help.

like image 383
Steve Horn Avatar asked Sep 19 '08 14:09

Steve Horn


3 Answers

This is based on .NET v1 event sequence, but it should give you the idea:

  • Initialize (Init event)
  • Begin Tracking View State (checks if postback)
    • Load View State (if postback)
    • Load Postback Data (if postback)
  • Load (Load event)
    • Raise Changed Events (if postback)
    • Raise Postback Events (if postback)
  • PreRender (PreRender event)
  • Save View State
  • Render
  • Unload (Unload event)
  • Dispose

As you can see, the loading of ViewState data back to the controls happen before the Load event. So in order for your dynamically-added controls to "retain" those values, they have to be present for the ASP.NET page to reload the values in the first place. You would have to re-create those controls at the Init stage, before Load View State occurs.

like image 127
icelava Avatar answered Sep 28 '22 00:09

icelava


I figured out yesterday that you can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.

Protected Overrides Sub LoadViewState(ByVal savedState As Object)
    MyBase.LoadViewState(savedState)
    If IsPostBack Then
        CreateMyControls()
    End If
End Sub
like image 45
Middletone Avatar answered Sep 28 '22 00:09

Middletone


I believe you'll need to add the UserControl to the PlaceHolder during the Init phase of the page life cycle, in order to get the ViewState to be filled in by the Load phase to read those values. Is this the order in which you're loading those?

like image 35
bdukes Avatar answered Sep 27 '22 23:09

bdukes