Steve C. Orr

Software Engineer, Web Developer, Database Designer
 
  

 




Q: How do I save the state of my controls between postbacks?

A: In many cases no action is required to save the state of controls between postbacks. When encapsulating existing controls within a user or custom control, they'll often save their own state just as they do when using them directly on Web pages. However, there are circumstances that will require custom data to be saved between postbacks. Imagine a simple control that contains only a LinkButton and a Label control. To save the number of times a user has clicked on the LinkButton and display that count in the Label control, a block of VB.NET code like this can be used in the code-behind:

Private Sub LinkButton1_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles LinkButton1.Click
    Dim i As Integer = CInt(ViewState("ClickCount"))
    i = i + 1
    >ViewState("ClickCount") = i
    Label1.Text = "Clicks: " & i.ToString
End Sub

This code saves the custom data value in ViewState, indexed under the name "ClickCount". This code sample gets any existing value out of ViewState, increments it, then puts the new value back into ViewState. Finally, the value is displayed in the Label control. Because each control is automatically given a unique naming container within ViewState, control developers don't need to worry about naming collisions between multiple instances of a control on the same page. Figure 1 illustrates the fact that each instance of a control automatically has its own unique "ClickCount" ViewState value.

Figure 1: Each instance of a control automatically gets a unique ViewState, so you needn't be concerned with giving each instance of a control a unique ViewState name.


 

(advertisement)