Tuesday, 14 March 2017



Retrieve Session Value in ASP.NET using C# with Example



Hi,I am Navid Shaikh today i am going to show you how to send (pass) Value one page to another page using Session   in Asp.net C#


The session state is used to maintain the session of each user throughout the application. Session allows information to be stored in one page and access in another page and support any type of object. In many websites we will see the functionality like once if we login into website they will show username in all the pages for that they will store username in session and they will access that session username in all the pages.

Whenever user enters into website new session id will generate for that user. This session Id will delete when he leave from that application. If he enters again he will get new session Id.


We can check this one with simple example for that create one new website and open Default.aspxpage and write the following  code



<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Asp.net Session State Example in C#</title>

</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>UserName:</td><td><asp:TextBox ID="txtUname" runat="server"/></td>
</tr>
<tr>
<td>Password:</td><td><asp:TextBox ID="txtPass" runat="server"/></td>
</tr>
<tr><td></td><td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></td></tr>
</table>
</div>
</form>
</body>
</html>


After that write the following code in button click Event


protected void btnSubmit_Click(object sender, EventArgs e)
{
Session["Username"] = txtUname.Text;
Session["Password"] = txtPass.Text;
Response.Redirect("Default2.aspx");
}


Add second page in project and write following code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> Second Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Default2.aspx</h3>
<table>

<tr>
<td>Your Username: </td><td><b><asp:Label ID="lblUname" runat="server"/></b></td>
</tr>
<tr>
<td>Your Password</td><td><b><asp:Label ID="lblPass" runat="server"/></b></td>
</tr>
<tr><td></td><td> </td></tr>
</table>
</div>
</form>
</body>
</html>

After that write the following code in Page Load Event

protected void Page_Load(object sender, EventArgs e)
{
     if(!IsPostBack)
     {
          lblUname.Text = Session["Username"].ToString();
          lblPass.Text = Session["Password"].ToString();
      }
}


No comments:

Post a Comment