Share via


retrieving a List<> from a session variable

Question

Tuesday, February 16, 2010 1:23 PM

I have List<> value which I save in a session variable. Later I want to retrieve
the list from the session variable. The problem I am having is that I don't know
how to retrieve my session data back into another List<>
Can someone help me out? I have a simple example below in the Page_Load method. I
save the list in a session variable and then try to retrieve it into another List<>

I am getting an implicit conversion error though. See my bolded comments in the code of
the Page_Load method below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default7 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<FileAttachement> fileAttachmentList = new List<FileAttachement>();

        FileAttachement fileAttachement = new FileAttachement();
        fileAttachement.Title = "My title";
        fileAttachement.FileName = "My Name";
        fileAttachement.Add(fileAttachement);

        Session["FileList"] = fileAttachementList;

        List<FileAttachement> MyfileAttachmentList = new List<FileAttachement>();
        // Next line gives an error
        MyfileAttachmentList = (fileAttachement)Session["FileList"];

       **// Error message, Cannot implicitly convert type 'FileAttachement'
       // to 'Systems.Collections.Generic.List<FileAttachement>
**    }
}

public class FileAttachement
{
    private string title;
    public string Title
    {
        get { return this.title; }
        set { this.fileName = value; }

    }

    private string fileName;
    public string FileName
    {
        get { return this.title; }
        set { this.fileName = value; }

    }

}

All replies (2)

Tuesday, February 16, 2010 1:27 PM ✅Answered

MyfileAttachmentList = (List<FileAttachement>)Session["FileList"];


Tuesday, February 16, 2010 3:52 PM ✅Answered

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var fileAttachmentList = new List<FileAttachement>();

            var fileAttachement = new FileAttachement {Title = "My title", FileName = "My Name"};
            fileAttachmentList.Add(fileAttachement);

            Session["FileList"] = fileAttachmentList;

            var myfileAttachmentList = new List<FileAttachement>();
            // Next line gives an error
            myfileAttachmentList = (List<FileAttachement>) Session["FileList"];

        }
    }

    public class FileAttachement
    {
        public string Title { get; set; }
        public string FileName { get; set; }
    }