Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 81.4k

question about Session

Jan 7 2023 3:08 PM

Hi,

this code works perfect (without the last line!). The elements of list<T> are retained by the Session variable after each postback. But i'm wondering how it can work without the last line: Session["time"] = time; . When a new element is added to the list, if Session["time"]  is not present, then it's not updated and doesn't contain the new element. According to me, the line time = (List<int>)Session["time"]; can't contain anyyhing. 

Any explanation for this: why is that line Session["time"] = time; not necessary?

Thanks

V

 

using System;
using System.Collections.Generic;

    public partial class WebForm : System.Web.UI.Page
    {
        List<int> time = new List<int>();

        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Focus();
            if (!Page.IsPostBack)
            {
                Session["time"] = time; // empty
            }
        }
        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            Label1.Text = "";
            time = (List<int>)Session["time"]; 
            time.Add(Convert.ToInt32(TextBox1.Text));
            time.Sort();
            for (int i=0;i< time.Count;i++)
            Label1.Text += time[i].ToString() + " ";
            TextBox1.Text = "";
            //Session["time"] = time; // works without this line
        }
    }


Answers (9)