In this article I will explain with an example, how to store (save) class object and retrieve Session value in ASP.Net using C# and VB.Net.
 
 

HTML Markup

The following HTML Markup consists of:
TextBox - For user inputs.
Button – For Save and retrieve Session value.
The Buttons has been assigned with an OnClick event handler.
<table>
    <tr>
        <td>Name:</td>
        <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td>Age:</td>
        <td><asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>
    </tr>
    <tr>               
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="OnSave" />
            <asp:Button ID="btnGet" runat="server" Text="Get" OnClick="OnGet" />
        </td>
    </tr>
</table>
 
 

Property Class

The class consists of following properties.
C#
public class PersonCS
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
VB.Net
Public Class PersonVB
    Public Property Name As String
    Public Property Age As Integer
End Class
 
 

Storing value in Session in ASP.Net

Inside the OnSave event handler, an object of the Person class is created and values of Name and Age properties are set.
Finally, the person object is set in the Session.
C#
protected void OnSave(object sender, EventArgs e)
{
    PersonCS person = new PersonCS()
    {
        Name = txtName.Text,
        Age = Convert.ToInt32(txtAge.Text)
    };
 
    Session["Person"] = person;
}
 
Inside the OnGet event handler the value of Session is retrieved and converted to Person class object.
protected void OnGet(object sender, EventArgs e)
{
    PersonCS person = (PersonCS)Session["Person"];
    string message = string.Format("Name: {0}.\\nAge: {1}", txtName.Text, Convert.ToInt32(txtAge.Text));
    ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('" + message + "');"true);
}
 
VB.Net
Protected Sub OnSave(ByVal sender As ObjectByVal e As EventArgs)
    Dim person As PersonCS = New PersonCS() With {
        .Name = txtName.Text,
        .Age = Convert.ToInt32(txtAge.Text)
    }
    Session("Person") = person
End Sub
 
Inside the OnGet event handler the value of Session is retrieved and converted to Person class object.
Protected Sub OnGet(ByVal sender As ObjectByVal e As EventArgs)
    Dim person As PersonCS = CType(Session("Person"), PersonCS)
    Dim message As String = String.Format("Name: {0}.\nAge: {1}", txtName.Text,Convert.ToInt32(txtAge.Text))
    ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('" & message & "');"True)
End Sub
 
 

Screenshot

Save Store and Retrieve value in ASP.Net
 

Downloads