What is View State and How it Works in Asp.Net

In this tutorial i will explain what is ViewState and uses of ViewState state with example in Asp.net using C#. View State is the method to preserve the Value of the Page and Controls between round trips. It is a Page-Level State Management technique. it  is used to maintain the state of controls during page postback. if we save any control values or anything in viewstate we can access those values throughout the page whenever it required.
So, Let's Create one example for Demonstration purpose.

Before start example you have to create one empty website.
For that Open Visual Studio >> click on "New Project" >> "Web" >> "ASP.NET Empty Web Application".

After then you have to create one web page. 

Now, Click on Solution Explorer >> right-click on the "ADD" >> "New Item" >> "Web Form" and add the name of webform like abc.aspx.

Now write following code in your .aspx file.

aspx code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>View State Example</title>
</head>
<body>
    <form id="form1" runat="server">
       <div>
 
           <asp:Label ID="Label1" runat="server" ForeColor="Green"></asp:Label>
           <br />
           <br />
           Book Name :<asp:TextBox ID="TextBox1" runat="server" Height="22px" Width="128px"></asp:TextBox>
           &nbsp;Author:<asp:TextBox ID="TextBox2" runat="server" Height="22px" Width="128px"></asp:TextBox>
           <br />
           <br />
           <asp:Button ID="Button1" runat="server" Text="Submit" Height="37px" OnClick="Button1_Click" Width="66px" />&nbsp
           <asp:Button ID="Button2" runat="server" Text="Restote" Height="37px" OnClick="Button2_Click" Width="66px" />
           <br />
       </div>
    </form>
</body>
</html>

C# Code For View State

protected void Button1_Click(object sender, EventArgs e)
   {
       ViewState["BookName"] = TextBox1.Text;
       ViewState["Author"] = TextBox2.Text;
       TextBox1.Text = TextBox2.Text = string.Empty;
       Label1.Text = "View State Done...!";
   }
   protected void Button2_Click(object sender, EventArgs e)
   {
       if (ViewState["BookName"] != null)
       {
           Label1.Text = "";
           TextBox1.Text = ViewState["BookName"].ToString();
 
       }
       if (ViewState["Author"] != null)
       {
           Label1.Text = "";
           TextBox2.Text = ViewState["Author"].ToString();
       }
   }
Demo:
View State Example in Asp.Net

Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon