Asp.net ViewState Example in C-Sharp

Share it Please
Here I will explain what is viewstate and uses of viewstate with example in asp.net using c# .

Description:-


In previous posts I explained What is the Dataset in ASP.NET, Difference between .NET Framework 4.5 and .NET Framework 4.0, What is Cloud Computing, Basics of ASP.NET . Now I will explain what is viewstate and uses of viewstate with example in asp.net using c# .


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.

.aspx 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Asp.net ViewState Example in C#, VB.NET</title></head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>ViewState Data:</td><td><b><asp:Label ID="lblViewStateDate" 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>

.cs 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string str = "Welcome to aspdotnetweb4u";
            if (ViewState["SampleText"] == null)
            {
                ViewState["SampleText"] = str;
            }
        }
    }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        lblViewStateDate.Text = ViewState["SampleText"].ToString();
    }
 }

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner

Blogroll