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.
Store the value in viewstate
Retrieve information from viewstate
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.
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();