• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 563
  • Last Modified:

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


  • 2
1 Solution
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.
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now