UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C# object to Session

Demo and Code for how to assign data list and controls to a session Asp.net c#

by Athil


Posted on 30 Mar 2017 Category: Asp.net Views: 620

Edited on 02 Jun 2017



DEMO

Hi, Here I am going to show how to add any object to a session in ASP.net, A session can hold any objects like Textbox, Label, Data etc.

Example for assigning textbox to a session and vice-versa.

Session["TextBox"] = TextBox1;
TextBox1 = Session["TextBox"] as TextBox;

 

For adding data object to session first I am going to add a data modal.

    public class User {
        public string Name { get; set; }
        public string Address { get; set; }
        public DateTime Datetime { get; set; }
    }

 

Here the class name I was given is User and it has three data members  Name, Address, Datetime

 

On Client Side
 

       Enter name and Address and click on add to session button<br />
        <br />
        Name:&nbsp;&nbsp;&nbsp; <asp:TextBox ID="txtNameSet" runat="server"></asp:TextBox>
   
        Address:
        <asp:TextBox ID="txtAddressSet" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
        <p>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add to Session" />
        </p>
        Name :<asp:TextBox ID="txtNameGet" runat="server"></asp:TextBox>
        <p>
            Address:
            <asp:TextBox ID="txtAddressget" runat="server"></asp:TextBox>
        </p>
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Retireve from Session" />

 

On Server Side

  public class User
        {
            public string Name { get; set; }
            public string Address { get; set; }
            public DateTime Datetime { get; set; }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            User ur = new User();
            ur.Name = txtNameSet.Text;
            ur.Address = txtAddressSet.Text;
            ur.Datetime = DateTime.Now;
            Session["UserDetails"] = ur;
            lblMessage.Text = "Added to session";
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            User ur = new User();
            ur = Session["UserDetails"] as User;

            ur.Name = txtNameGet.Text;
            ur.Address = txtAddressget.Text;

        }


Leave a Comment:


Advertisement