Introduction:

  • In this article we will learn how to use viewstate in asp.net or what is viewstate in asp.net or why viewstate in asp.net with example.

  • Description:

In Asp.net View State is the method it is used to maintain the state of controls during page postback and if we save any control like textbox, dropdown  values  in viewstate. we can access those values through the page when we required .let’s see below simple example

 

ViewState.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewState.aspx.cs"
Inherits="ViewState.ViewState" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            UserID: <asp:TextBox ID="txtUserID" runat="server" Width="189px">
       
      </asp:TextBox><br /><br />
         Password: <asp:TextBox ID="txtPassword" runat="server"
    
       Width="189px"  TextMode="Password"></asp:TextBox><br />
       <br />
        <asp:Button ID="btnSubmit" runat="server"
        OnClick="btnSubmit_Click" Text="Submit" />
       
   <asp:Button ID="btndefault" runat="server" Text="Restore"
  
    OnClick="btndefault_Click" />
            </div>
    </form>
</body>
</html>

 

 ViewState.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace ViewState
{
    public partial class ViewState : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                txtUserID.Text = "ADI0004";
                txtPassword.Attributes["value"] = "123456";
                ViewState["UserID"] = "ADI0004";
                ViewState["Password"] = "123456";
 
            }
 
        }
 
        protected void btndefault_Click(object sender, EventArgs e)
        {
            if(ViewState["UserID"] != null)
                txtUserID.Text = ViewState["UserID"].ToString();
            if(ViewState["Password"] != null)
                txtPassword.Attributes["value"] = ViewState["Password"].ToString();
        }
 
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
 
        }
    }
}

 

Output:



0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like