Session Example Code -

How to use session in

Snippet Code

Rate this page :
  [ 0 votes]

This session code helps you to create session for the user and maintain it. Here, the sample code allows you to create retrieve and remove session.

index.aspx: -------------- <form id="form1" runat="server"> <div> <fieldset> <div> Userame: <asp:TextBox ID="txtUserName" runat="server" MaxLength="50"></asp:TextBox> <asp:RequiredFieldValidator ID="rfvFirstName" runat="server" Display="Dynamic" CssClass="validator" ControlToValidate="txtUserName" ErrorMessage="Username is required"></asp:RequiredFieldValidator> </div> <div> <asp:Button ID="btnCreateSession" runat="server" Text="Click to Create Session" onclick="btnCreateSession_Click" /> ampnbsp; <asp:Button ID="btnRetrieveSession" runat="server" CausesValidation="false" Text="Click to Retrieve Session Value" onclick="btnRetrieveSession_Click" /> ampnbsp; <asp:Button ID="btnRemoveSession" runat="server" CausesValidation="false" Text="Click to Remove Session Value" onclick="btnRemoveSession_Click" /> </div> <div> Value stored in Session: <strong><asp:Label ID="lblSessionValue" runat="server"></asp:Label></strong> </div> </fieldset> </div> </form> index.aspx.cs: ----------------- using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCreateSession_Click(object sender, EventArgs e) { Session["Username"] = txtUserName.Text.Trim(); } protected void btnRetrieveSession_Click(object sender, EventArgs e) { DisplaySessionValue(); } protected void btnRemoveSession_Click(object sender, EventArgs e) { Session.Remove("Username"); DisplaySessionValue(); } private void DisplaySessionValue() { if (Session["Username"] != null) lblSessionValue.Text = Convert.ToString(Session["Username"]); else lblSessionValue.Text = "No Value has been stored in session"; } }


Ask Questions

Ask Question