Search code examples
asp.netpostbackviewstatedynamic-controls

Keep a value accessible in Page.Init between postbacks in asp.net


Ok, I've already learned that in order to keep the dynamic (created) controls and their viewstate in asp.net we must (re)create them in the Page init event, so they already exist within the page's control hierarchy before the view state is loaded.

As it says in this article.

There is no problem to achieve this behaviour if the criteria to create these controls is outside the web environment, for example a database. But what should I do if what I use to decide how many dynamic controls I have to create is actually a value that is in the controls?

I try to explain it with an example, maybe it's clearer:

Let's say that we have a textbox and two buttons. In the textbox I write the number of how many dynamic controls I want to create, for example 4 checkbox. When I hit the button1 the controls should be created. No problem. Then I check some checkboxes and hit the button2 just to fire a postback. Now I should recreate the controls in the page init event, like we said before, in order to maintain the controls and their state.

And here comes the problem. Because of I'm in the init stage I have no viewstate so I'm no able to access the value in the textbox that tells me how many dynamic checkbox should I create.

I thought that storing the value in the session object would do the trick, but it doesn't. The session object is no accessible as well.

Where can I save the value that it'll be accessible from the init event too?

Thanks and sorry for the long post!


Solution

  • First thing - textbox value is not stored/retrieved from view state, you cannot get textbox value from viewstate. Coming to actual problem, here is the sequence of (imp) events init -> load view state -> bind postback data -> page load. You can retrieve textbox value only after bind postback data event (which actually takes posted data and binds to the textbox control). In init only option is to use Request.Form{"textboxid"] to get the textbox value.