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
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" 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>
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
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" 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>
Default.aspx.cs
Now add following namespaces in your codebehind
using System;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string str = "Nikhil Sangani";
if (ViewState["SampleText"] == null)
{
ViewState["SampleText"] = str;
}
}
}
protected void btnClick_Click(object sender, EventArgs e)
{
lblString.Text = ViewState["SampleText"].ToString();
}
Comments
Post a Comment