ViewState in ASP.Net

ViewState Example in ASP.Net

ViewState is a important client side state management technique. ViewState is used to store user data on page at the time of post back of web page.

ViewState does not hold the controls, it holds the values of controls. It does not restore the value to control after page post back. ViewState can hold the value on single web page, if we go to other page using response.redirect then ViewState will be null.

  • ViewState stores data on single page
  • ViewState is client side state management technique
  • Session stores data on whole website pages
  • Session is a server side state management technique

ViewState syntax same as Session, Session is a server side object while ViewState is a client side object. Session can stores values across on multiple pages while ViewState stores values on single page.

Viewstate Example

Store the value in viewstate

ViewState[“name”]=”Meera Academy”;

Retrieve information from viewstate

string value=ViewState[“name”].ToString();

View State Example in ASP.Net

Open visual studio and design web form with two button control, a textbox and a label control as shows in below figure.

Here,  we have two button control one for a clear textbox value and second one for a retrieve the same textbox value after clearing it. Before clearing textbox value store it in ViewState[“name”] and after clearing it get value from ViewState[“name”] and display  in label  while clicking display value button.

ViewState example in
ViewState Example in ASP.Net

C# Code for above example

 protected void Page_Load(object sender, EventArgs e)

    protected void btnclear_Click(object sender, EventArgs e)
        ViewState["name"] = txtname.Text;
        txtname.Text = "";
    protected void btndisplay_Click(object sender, EventArgs e)
        lbl.Text = ViewState["name"].ToString();

Related ASP.Net Topics :

Cookies in C#.Net
Context Object in C#.Net

Subscribe us

If you liked this post, then please subscribe to our YouTube Channel for more video tutorials.

We hope that this c# tutorial helped you to understand about ViewState in C#.

Next tutorial we will understand about Query String in C#.

8 thoughts on “ViewState in ASP.Net

Leave a Reply

Your email address will not be published. Required fields are marked *