Wednesday 10 August 2011

Storing and Retrieving values from Session

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.


//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
        }

No comments:

Post a Comment