Q: How do I store a value between PostBacks?
A: You might have noticed that variables’ values you’ve carefully set in a page’s
code-behind are wiped out when the page posts back to itself. Although this can
be annoying and confusing to developers accustomed to Windows application development,
it can be easily solved with a couple lines of code. Simply store the variable’s
value in ViewState before PostBack, and it will be waiting there for you to retrieve
after the PostBack:
'Store the value in ViewState before PostBack
ViewState("MyVariable") = MyString
'Retrieve the value from ViewState after PostBack
MyString = ViewState("MyVariable").ToString
You might be interested to know that ASP.NET stores this (and all other ViewState
values) in an encoded hidden text element within the page’s form. Because this data
is transferred between the client and server between each PostBack, you shouldn’t
fill it with any more data than is necessary. Storing a few simple values won’t
be a problem, but storing large DataSets and large structures tends to be more problematic
from a performance perspective.