Wednesday 4 April 2012

View State Example



To implement this concept you need to follow the below steps :
 
Step1:
Create a new Asp.net website in Visual Studio and write the following html code in the design part of the Default.aspx page.

Default.aspx Page :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <table class="style1">
        <tr>
            <td class="style3">
                <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
            </td><td>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
        </tr><tr>
            <td class="style4">
                <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            </td>
            <td class="style2">
                <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
            </td>
        </tr><tr>
            <td class="style3">
                <asp:Label ID="lblCountry" runat="server" Text="Country"></asp:Label>
            </td>
            <td>
                <asp:DropDownList ID="ddlCountry" runat="server">
                    <asp:ListItem>India</asp:ListItem>
                    <asp:ListItem>Africa</asp:ListItem>
                    <asp:ListItem>Andaman</asp:ListItem>
                    <asp:ListItem>Lanka</asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr><tr>
            <td class="style3">
                &nbsp;</td>
            <td>
                <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
                    Text="Submit" />
            </td></tr>
    </table>
    <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>



Step2:
Now open the Default.aspx.cs page and write the following source code.

Default.aspx.cs Page :


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)
    {
        ViewState["Password"] = txtPassword.Text;
        if (ViewState["Password"] != null)
        {
            txtPassword.Attributes.Add("value", ViewState["Password"].ToString());
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string Name, Password, Country;
        Name = txtName.Text;
        Password = txtPassword.Text;
        Country = ddlCountry.SelectedItem.Text;
        lblMsg.Text = string.Format("Name={0}<br>Password={1}<br>Country={2}", Name, Password, Country);
    }
}



Step3:
Now build the Solution and Debug it for the output.

Output Page :


No comments:

Post a Comment