Firstly thanks to Paul Wilson whose articles have enlightened me about the ViewState Object.
This listing (an extract of Paul's article) explains events that take place in a client requested aspx page.
There are many programmers like me who would like to create dynamic controls
in a page on/after the Page_load event and still use the ViewState to store and
retrieve information about the controls value. Though the saving of information
is easy the retrieval part is not easy. By defining a functions in the PageClass
we can store and get information of all the dynamic controls that need to save
information in the ViewState object.
Using the code
Step 1: Create a page class
<P>Public Class BasePage</P><P> Inherits System.Web.UI.Page</P><P> End Class</P>
Step 2: Declare the following functions in this class
<P>Public Function SaveCtrlViewState(ByVal ID As String, ByVal value As Object)</P><P> Me.ViewState(ID) = value</P><P>End Function </P><P> </P><P>Public Function GetCtrlViewState(ByVal ID As String) As Object</P><P> Return Me.ViewState(ID)</P><P>End Function</P>
Step 3: Create a WebControl Class
<P>Public Class DynTextBox</P><P> Inherits System.Web.UI.WebControls.TextBox</P><P> Private _page as BasePage </P><P> </P><P> Protected Overrides Sub OnInit(ByVal E As System.EventArgs)</P><P> MyBase.OnInit(E) </P><P> _page = CType(Me.Page, BasePage) </P><P> End Sub</P><P> Public Sub DoSomething()</P><P> _page.SaveCtrlViewState(Me.ID, value)</P><P> End Sub</P><P> Public Sub DoSomethingMore()</P><P> Dim oValue As Object = _page.GetCtrlViewState(Me.ID)</P><P> End Sub</P><P> </P><P>End Class</P>
Step 4: Create a page that is derived from BasePage
Step 5: Create an instance of DynTextBox control in any event/Function (before Render)
in your Page
Step 6: Save the ViewState of the control by calling DoSomething function.
Step 7: Postback your page (have a Submit button)
Step 8: Create your control and call the function <DoSomethingMore> to get back the
You finally have the flexibility to save your dynamic controls ViewState and get it back
without worrying much about the events that happen in your page.