ViewState in ASP.NET

ViewState in ASP.NET


Posted in : ASP.Net Posted on : December 18, 2010 at 6:06 PM Comments : [ 0 ]

In this article we will introduce with ViewState in ASP.NET

ViewState in ASP.NET

ViewState is the means of storing the state of server controls between post backs. ViewState is just like HiddenField. In this example we use the ViewState.

ViewState.aspx (Design Page):

ViewState.aspx (source code):

<%@ Page Title="" Language="C#" MasterPageFile="~/RoseindiaMaster.master" AutoEventWireup="true"
CodeFile="ViewState.aspx.cs" Inherits="ViewState" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div>
<h2 style="color: Green">
View State in ASP.NET 4, C#</h2>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large" ForeColor="#000099" />
<br />
<br />
<strong>Your Name:</strong>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Save data" OnClick="Button1_Click" />
&nbsp;&nbsp;
<asp:Button ID="Button2" runat="server" Text="Read data" OnClick="Button2_Click" />
</div>
</asp:Content>

ViewState.aspx.cs (C# code file):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ViewState : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Name"] = TextBox1.Text.ToString();
Label1.Text = "Your name saved in ViewState."; 
}
protected void Button2_Click(object sender, EventArgs e)
{
string name = (string)ViewState["Name"];
Label1.Text = "Hi " + name + "! we found your name in ViewState."; 
}
}

Output:

Download source code
Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics