Learn ASP.NET MVC How to's for free here.
ITFunda.Com
Your details are safeBuyer's Satisfaction Contact Us
 Welcome Guest | Register | Login Why online training? | Buyers FAQs | Testimonials | Contact us 

Subscribe


Subscribe to Tutorials feed

Our Quality Professors


Our professors includes
Contact us for training ...

Technology Tags


ADO.NET AdRotator ASP.NET ASP.NET-AJAX Authentication-and-Authorization---LoginView BulletedList Button Caching Calendar Chart CheckBoxList Cookies CSharp CSS Cusotm-Control Debugging-and-Tracing DetailsView DropDownList-and-ListBox DropDownList-and--ListBox Error-handling FileUpload Forms-Authentication GridView HiddenField HTML HyperLink Image ImageButton ImageMap Javascript jQuery jQuery-Ajax jQuery-Attributes jQuery-effects jQuery-Effects jQuery-Events jQuery-How-to-Solution jQuery-Manipulations jQuery-Selectors jQuery-Traversing Label-and-Literal LinkButton ListView Localization-and-Globalization Login LoginName LoginStatus LoginStatus-and-LoginName-and-other-controls LoginView MasterPage Menu Meta-tags Panel PlaceHolder RadioButtonList Repeater Security Session-Management TextBox Themes-and-Skins Url-Routing User-Control Validations visual-studio Webconfig Working-with-Files-and-Folders

Search Tutorials

Keyword
eg. asp.net

Announcements

More ...


 

How to use Session variables?


by: Itfunda Product Type: Tips and Tricks (Books) Technologies: ASP.NET  Session-Management 

Session data is a user specific data stored into the server memory. By default when we store the data into the session, it is stored into the Web server memory and that is called In-Proc session. To store data into session and retrieve data from session, we can follow this approach.

ASPX Page
    <asp:Label ID="lblMessage" runat="server" EnableViewState="false" />
    <div>
        <asp:DetailsView ID="DetailsView1" runat="server" EnableViewState="false" />
    </div>
    <p><asp:Button ID="btnClear" runat="server" Text="Clear Session" OnClick="ClearSession" /></p>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GetData(1);
    }
}

private void GetData(int autoId)
{
    DataTable table = new DataTable();

    if (Session["MyData"] != null)
    {
        table = (DataTable)Session["MyData"];
        lblMessage.Text = "Getting from Session";
    }
    else
    {
        // get the connection
        using (SqlConnection conn = new SqlConnection(_connStr))
        {
            // write the sql statement to execute
            string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail WHERE AutoId = @AutoId ORDER By AutoId";
            // instantiate the command object to fire
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                // get the adapter object and attach the command object to it
                using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                {
                    SqlParameter prm = new SqlParameter("@AutoId", SqlDbType.Int);
                    prm.Value = autoId;
                    cmd.Parameters.Add(prm);
                    // fire Fill method to fetch the data and fill into DataTable
                    ad.Fill(table);
                }
            }
        }
        Session["MyData"] = table;
        // set the time out to 40 minutes after that this session variable should expire
        Session.Timeout = 40;
        lblMessage.Text = "Getting from Database";
    }
    // specify the data source for the GridView
    DetailsView1.DataSource = table;
    // bind the data now
    DetailsView1.DataBind();
}

protected void ClearSession(object sender, EventArgs e)
{
    Session.Remove("MyData");
    // to cancel all the current sessionn for this user call
    //Session.Abandon();
}
In the above code snippet, on the .aspx page we have an asp:Label, asp:DetailsView and an asp:Button. In the Page_Load we are calling GetData method to check if there is some data into the Session variable Session[“MyData”], if not we are using ADO.NET to retrieve the data and saving into the Session[“MyData”] session variableand specifying Session.Timeout to 40 (this will expire this session variable after 40 minutes and its data will be lost). If Session[“MyData”] is not null we are unboxing the session variable to the table variable of DataTable type and the same table is being used to populate the DetailsView.

On the click of “Clear Session” button; we are removing the “MyData” session key from the session that will remove the data “MyData” key value from the session object (If we will use Session[“MyData”] in the code behind now we shall get null value) . If we want to cancel all session of that particular user, we can call Session.Abandon method.

OUTPUT

First time request to this page



Subsequent request of this page



This post is the part of following product

.NET How to Tips and Tricks (700+)

.NET How to Tips and Tricks (700+) This ".NET How to Tips and Tricks" contains solutions of hundreds of technical problems related with ASP.NET, ASP.NET MVC, SQL Serer, jQuery etc. that help you to develop real time .NET projects easily. It has following features
  • Video tutorials
  • Demo projects source code
  • eBook with to-the point explanations & output
prepared by Sheo Narayan (Ex Microsoft MVP).

 Latest tutorials

 Posts from Itfunda


Share this to:

Facebook Twitter LinkedIn Google+ Pinterest Email Addthis


About Us | Contact Us | Partners | Privacy Policy | Terms and Conditions | Buyer's FAQs | Seller's FAQs | Currency Converter | Go Top

Notice: If you found someone plagiarising our content/materials, kinldy let us know.

© SN ITFunda Services LLP. Site design and layout is copyright to SN ITFunda Services LLP.
Copying or duplicating or mimicking the site design and layout is prohibited and will be treated as a legal offence and will be prosecuted.
Logos, company, product, service or other names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 16102020 | 5/29/2023 3:54:58 AM