25 June 2012

ViewState in Asp.Net

What is ViewState?

ViewState is used to maintain the state of controls during page postback and if we save any control values or anything in viewstate we can access those values throughout the page whenever it required for that check below simple example


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>View State in asp.net Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>ViewState Data:</td><td><b><asp:Label ID="lblString" runat="server"/></b></td>
</tr>
<tr><td></td><td> <asp:Button ID="btnClick" runat="server" Text="Get ViewState Data"
onclick="btnClick_Click"/></td></tr>
</table>
</div>
</form>
</body>
</html>
Now add following namespaces in your codebehind

C# Code


using System;

After that write the following code in button click


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string str = "Welcome to Aspdotnet-Suresh Site";
if(ViewState["SampleText"]==null)
{
ViewState["SampleText"] = str;
}
}
}

protected void btnClick_Click(object sender, EventArgs e)
{
lblString.Text = ViewState["SampleText"].ToString();
}