Viewstate textbox


I have a textbox with id txtTest. that gets populated from the DB. What i want to do is that once the page has finished loading I want to get the value of the text box and save it in a viewstate. and then use that variable later.

Please Help


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

If you use a textbox in ASP.NET it will automatically use the viewstate already. You can get the value from the textbox at any time. Make sure to put

if (IsPostBack) {
   // load text here

inside the page_load where you load your data to prevent the text to be overridden as soon as you want to do something with it using a button of some sort. You can get your text from the viewstate using:

string mytext = txtTest.Text;
R8VIAuthor Commented:
Ahhh thanks for that, but my fault i didnt mention one thing that is what happens is when the page gets loaded the text box displays a value from the database. Then the user can edit that text box and hit save. So what I want to do is to be able to store the orginal value which gets loaded from the database.

Please Help


Not sure why you need viewstate for doing that, but here's how to (just after you bind that value from your db):

ViewState["myTextValueOriginal"] = txtTest.Text;
retrieving the value is like this:

string originalText = (string) ViewState[myTextValueOriginal"];
the ViewState object is available from all over your page.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
You can access the viewstate directly:

ViewState["txtTest"] = "aaaaa";

and then get back the value:

string x = (string) ViewState["txtTest"];

but be careful, if the ViewState["txtTest"] is null, type cast may fail if you cast e.g. to DateTime.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.