How to Retrieve Session Values in ASP.Net?

Posted by Deepa Ranganathan
4
Jan 6, 2016
321 Views

If you are planning on storing user specific information in ASP.Net, then you need to use the session objects. You might want to get all the values that you have stored in a particular session object. Let’s say there are three page.aspx, and you are storing values in each of these pages. Let’s say one of the page.aspx is used to print the session keys with its values.

You need to understand the process to retrieve the session values in ASP.Net

Let’s first check the individual pages

In this Page1.aspx.cs, you will store one value ID for the session

Session["Id"] = "1";

Similarly, in Page2.aspx.cs

Session["Name"] = "XYZ"; 

In, Page3.aspx.cs, you will retrieve the values that you have stored in the preceding pages.

You have three methods of retrieving the session values when you are dealing with ASP.Net. Here we will discuss each of the methods, and then zero down on the output

Method One

In this method, you will be looping the session.contents in order to get the keys used in the session. Using these keys, you will be able to retrieve the session values

protected void Page_Load(object sender, EventArgs e)   

{   

    foreach(string key in Session.Contents)    

    {   

        string value = "Key: " + key +", Value: " + Session[key].ToString();   

   

        Response.Write(value);   

    }   

}

Method Two

In this method, you will first count the number of keys present in the current session object. Once, you have the number in hand, you will be able to retrieve the value

protected void Page_Load(object sender, EventArgs e)   

{   

    for (int i = 0; i < Session.Count; i++)   

    {   

        string value = "Key: " + Session.Keys[i] +

        ", Value: " + Session[Session.Keys[i]].ToString();   

   

        Response.Write(value);   

    }   

}

Method 3

Here, you will directly loop the session that returns the key, and use it to retrieve the session values

protected void Page_Load(object sender, EventArgs e) 

{   

    foreach (string s in Session)   

    {   

        string value = "Key: " + s + ", Value: " + Session[s].ToString();   

   

        Response.Write(value);   

    }   

}

The Output: Retrieval of Values

“Key:Name, Value:XYZ”

This value is retrieved using either of the three methods specified above

 

Conclusion

Retrieving the session values is easy if you use one of the three methods specified here. Of course, you will need to ensure you use the code properly. Hire ASP.Net Developers to ensure that the coding is done without any errors, so that the output retrieved is exactly what you want.

Comments
avatar
Please sign in to add comment.