65.9K
CodeProject is changing. Read more.
Home

Save and Get values of Dynamically created controls from ViewState

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.04/5 (14 votes)

Nov 14, 2003

1 min read

viewsIcon

80136

This articles describes you a simple method to save and get values of dynamically created controls in a Web Page from the ViewState Object

Introduction

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.

Listing1

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

Public Class BasePage

Inherits System.Web.UI.Page

End Class

Step 2: Declare the following functions in this class 

Public Function SaveCtrlViewState(ByVal ID As String, ByVal value As Object)

Me.ViewState(ID) = value

End Function

Public Function GetCtrlViewState(ByVal ID As String) As Object

Return Me.ViewState(ID)

End Function

Step 3: Create a WebControl Class

Public Class DynTextBox

Inherits System.Web.UI.WebControls.TextBox

Private _page as BasePage

Protected Overrides Sub OnInit(ByVal E As System.EventArgs)

MyBase.OnInit(E)

_page = CType(Me.Page, BasePage)

End Sub

Public Sub DoSomething()

_page.SaveCtrlViewState(Me.ID, value)

End Sub

Public Sub DoSomethingMore()

Dim oValue As Object = _page.GetCtrlViewState(Me.ID)

End Sub

End Class

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

control's ViewState

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.