In this article I will explain with an example, how to retrieve
Session value in
ASP.Net using C# and VB.Net.
HTML Markup
The following HTML Markup consists of:
Button – For submitting the Form.
The Button has been assigned with an OnClick event handler.
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="OnGet" />
Property Class
The class consists of following properties.
C#
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
VB.Net
Public Class Person
Public Property Name As String
Public Property Age As Integer
End Class
Storing value in Session in ASP.Net
Inside the Page_Load event handler, an object of the Person class is created and values of Name and Age properties are set.
Finally, the
Person class object is set in the
Session.
C#
protected void Page_Load(object sender, EventArgs e)
{
Person person = new Person()
{
Name = "Mudassar Khan",
Age = 35
};
Session["Person"] = person;
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim person As Person = New Person()With {
.Name = "Mudassar Khan",
.Age = 35
}
Session("Person") = person
End Sub
Retrieving Session Value in ASP.Net
Inside the
OnGet event handler, the value of
Session is retrieved and converted to
Person class object.
C#
protected void OnGet(object sender, EventArgs e)
{
Person person = (Person)Session["Person"];
}
VB.Net
Protected Sub OnGet(ByVal sender As Object, ByVal e As EventArgs)
Dim person As Person = CType(Session("Person"), Person)
End Sub
Screenshot
Downloads