Thursday 18 July 2013

Asp.net Session With Example

Here i explain asp.net session using c#.
Session state is mainly used to transfer values from one page to other without storing/retrieving  values from database.
In this tutorial two files one is first.aspx and other is second.aspx.

first.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="first.aspx.cs" Inherits="dreamtheweb.first" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="TextBox1" runat="server">Fname</asp:TextBox>
 <br />  <br />        <asp:TextBox ID="TextBox2" runat="server">lanme</asp:TextBox>
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <br />
  <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_click" />        <br />
   </div>
    </form>
</body>
</html>
first.aspx.cs page
Add  session statement inside button click ie,
  protected void Button1_click(object sender, EventArgs e)
        {
            Session["fname"] = TextBox1.Text;
            Session["lname"] = TextBox2.Text;
            Response.Redirect("second.aspx");
        }

The second.aspx page 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="second.aspx.cs" Inherits="dreamtheweb.second" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

For accept session values insert the below code in pageload section ie
protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Session["fname"].ToString();
            Label2.Text = Session["lname"].ToString();
          
             
            }
If you enjoy and work this post please support this blog and visit again

0 comments:

Post a Comment