Hi
There are a few options that you can implement to maintain state between
postbacks. As you mentioned ViewState we can take a look at this one first.
The first thing to note about ViewState is that it can get pretty large and
is rendered out to the page in the form of an encrypted string, so you
should use with caution. If you are only storing the value of one variable
then this will not cause any problems at all but if you were to start
storing large collections then you may start hitting some performance
issues. The second thing to note is that ViewState must be enabled for your
page in order for you to store your variable value. ViewState is enabled by
default but can be disabled by adding ViewState = "False" to your page
declaration.
So assuming that you have ViewState enabled, you could use code similar to
the following to store and retrieve your variable value:
<code>
Dim myNumber As Int32 = 0
'Determine if the variable value exists in ViewState and if it does, assign
'the value to the myNumber variable
If ViewState("MyNumberVariable") IsNot Nothing Then
myNumber = Convert.ToInt32(ViewState("MyNumberVariable"))
Else
'As the myNumber varaible does not exist in view state, add it.
ViewState.Add("MyNumberVariable", myNumber)
End If
'Increment the myNumber variable by one and display it's value on the page
myNumber += 1
numberLabel.Text = myNumber.ToString
'Store the current value of the myNumber variable in view state
ViewState("MyNumberVariable") = myNumber
</code>
Another option that you could take should you not wish to use ViewState is
to use the User's Session. This works similarly to ViewState from a
syntactical point of view and the only change to make to the above code is
to replace ViewState with Session. However, you should also be careful when
using Session variables as all values held in Session are stored in your Web
Servers memory and are unique to each visitor to your site. So should you
have a lot of visitors and a lot of Session values then you could seriously
hamper the performance of your site. There are workarounds to this such as
using a database to store your Session values.
One other thing to look into is ControlState. ControlState works very much
like ViewState but rather than being a mechanism for storing values at page
level, it is instead a mechanism for storing values at control level. So for
example, if you were creating a UserControl and you are not sure whether the
page hosting the UserControl will have ViewState enabled or disabled, you
can rest assured that your control's storage mechanism will work as you are
using ControlState which the hosting page has no control over.
HTH