Storing and Retrieving values from Session in asp.net


       Storing and Retrieving values in session are quite similar with ViewState. We can interact with Session State with  System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with Asp.Net Pages.
Following code is used for storing a value to session

//Storing UserName in Session
       Session["UserName"] = txtUser.Text;
Now, let see how we can retrieve values from Session
  //Check weather session variable null or not
        if (Session["UserName"] != null)
        {
            //Retrieving UserName from Session
            lblWelcome.Text = "Welcome : " + Session["UserName"];
        }
        else
        {
         //Do Something else
        }

we can also store some other object in Session. Following Example shows how to store a DataSet in session.

   //Storing dataset on Session
        Session["DataSet"] = _objDataSet;

and following code shows how we can retrieve that dataset from the session 
//Check weather session variable null or not
             if (Session["DataSet"] != null)
        {
            //Retrieving UserName from Session
            DataSet _MyDs = (DataSet)Session["DataSet"];
        }
        else
        {
            //Do Something else
        }


0 comments:

Post a Comment