We can manage a state with the following methods:
- ViewState
- Session
- Application
- Cookie
ViewState:
ViewState is used for retaining the value of the current page.
Life of ViewState is a life of the current page. Switching to otherpage leads to the lastpage viewstate value to expire. Its value gets changed from one execution of a page to another.
ViewState is enabled or disabled on the page and control specific also. Its very flexible to ON / OFF. You can check viewstate on executed ASP.NET page by viewsource from browser. There you can find _VIEWSTATE kind of hidden field.
ViewState increases the size of the page because page and page control value store in it. That's why sometimes we avoid using ViewState.
For lightweight value storage is very easy and fast to use.
Step by Step implementing and using VIEWSTATE in page
Create a new ASP.NET website project.
Go to File, New, then WebSite and give the name “ViewStateSample”
Right click on project, select ADD, ADD NEW ITEM, then WebForm from list of item. I added web-form with default name, page name is “DEFAULT.ASPX”
How to enable and disable the ViewState on Page level
Double click on Default.aspx page and click Source option.
Page Level ViewState settings
Open properties window by pressing shortcut key CTRL+W+P , Move the cursor at the top of the page and there this code is written.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
As your cursor reaches the above line your property window will display the current properties of ASP.NET page.
You will get two types of value for selection TRUE and FALSE.
I am going to select TRUE for ON viewstate on my page. As I selected EnableViewState = True, the ASP.NET page value is changed and this will set like the following:
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableViewState="True" %>
Control Level ViewState settings:
Now, I had inserted a TextBox control on page, we can enable or disable the ViewState on control level also.
- <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Click on TextBox script of ASP.NET and check Property Window.
ViewState with the following properties:
- Count: To get number(s) of items in the ViewState.
- Keys: To get all the keys name defined for ViewState.
- Values: To get all the values of the items in the ViewState.
There are two ways to Add or Update a View State Item.
- Syntax:
- ViewState.Add(“string Key”,object value)
Example:
- ViewState.Add(“UserAddress”,txtAddress.Text)
- Syntax:
- ViewState[“string Key”] = object value
Example:
- ViewState[“UserAddress”] = txtAddress.Text
Retrieves the Value from ViewState
txtAddress.Text = (string)ViewState[“UserAddress”]
or
txtAddress.Text = ViewState[“UserAddress”].ToString();
or
txtAddress.Text = Convert.ToString(ViewState[“UserAddress”]);
Removes an item from ViewState
ViewState.Remove(“UserAddress”)
Clear all items from ViewState
ViewState.Clear