0

I populate a collection in a UserControl which then creates dynamic LinkButton controls from the collection. When one is clicked, on postback, the collection is empty. Is this behavior by design or is there something I can do to keep the collections populated on postback without re-populating them in code? Do I need to re-query in the forms postback?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Metaphor
  • 6,157
  • 10
  • 54
  • 77
  • All variables are disposed at the end of a page's lifecycle. That's by design, it's in the nature of the [stateless HTTP](http://en.wikipedia.org/wiki/Stateless_protocol). – Tim Schmelter Oct 05 '13 at 20:08
  • Yet, variables defined on the ASP.NET pages are intact on postback. What mechanism is responsible for that? Why would usercontrols be treated differently? – Metaphor Oct 05 '13 at 20:12
  • @Metaphot: there's no difference between a page and a `UserControl`. Maybe you have a static field which will not be destroyed. However i strongly recommend against using a static field in a multi threading environment like ASP.NET. – Tim Schmelter Oct 05 '13 at 20:14
  • Controls that are declared static will be recreated automatically on postbacks, dynamically created controls must be recreated manually on postback. – Tim Schmelter Oct 05 '13 at 20:20

2 Answers2

2

Every variable defined in a class inheriting Web.UI.Page will be destroyed at the end of the Page-Lifecycle(incl. controls and fields), hence it will be null at postback if you don't reinitialize it.

One way to persist it across postbacks is to store it in a Session-variable.

You will find a complete list of all options on how to persist variables across postbacks here: http://msdn.microsoft.com/en-us/magazine/cc300437.aspx

  • Application
  • Cookies
  • Form Post / Hidden Form Field
  • QueryString
  • Session
  • New State Containers in ASP.NET
  • Cache
  • Context
  • ViewState
  • Web.config and Machine.config Files Conclusion

It's the nature of HTTP that it is stateless.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You need to persist the information in ViewState and recreate the controls when the ViewState is loaded after postback. For example, you could store number of buttons created and then recreate them.

See a similar solution at https://stackoverflow.com/a/15497035/1711598

Community
  • 1
  • 1
Knaģis
  • 20,827
  • 7
  • 66
  • 80