J S
J S

Reputation: 97

List String Session Variables in ASP.NET

I'm trying to make a program in ASP.net where a user enters details in a textbox on page 1 (default.aspx), clicks a button and it appears in a listbox in page 2 (about.aspx).

I'm trying to make it so the user can enter as many thing into the textbox on page 1 and they will all appear in the listbox in page 2.

Code on page 1:

public void Button1_Click(object sender, EventArgs e)
{
    people = Session["mySession"] as List<string>;
    people.Add(TextBox1.Text);
}

Code on page 2:

protected void Page_Load(object sender, EventArgs e)
{
    var myList = Session["mySession"] as List<string>;
            ListBox1.Text = string.Join(",", myList);
}

Any help would be great.

Upvotes: 1

Views: 9339

Answers (2)

Dmytro
Dmytro

Reputation: 1600

You have to check, if there is anything in your session... On Button click:

people = Session["mySession"] as List<string>;
//Create new, if null
if(people == null) 
    people = new List<string>();

people.Add(TextBox1.Text);

Session["mySession"] = people;

That is first. Second, on page #2 you have to do, on Page Load:

people = Session["mySession"] as List<string>;
//Create new, if null
if(people == null) 
people = new List<string>();
ListBox1.DataSource = people;
ListBox1.DataBind();

Of course, it's better, if you move to some static method this part, to resolve code duplication:

public static List<string> GetPeopleFromSession(){
    var people = HttpContext.Current.Session["mySession"] as List<string>;
    //Create new, if null
    if(people == null) 
        people = new List<string>();
    return people;
}

Upvotes: 4

BrokenGlass
BrokenGlass

Reputation: 160892

The problem is here:

ListBox1.Text = Session["mySession"] as List<string>;

You can't convert a list of strings to a string - you could on the other hand decide to display all of them e.g.

var myList = Session["mySession"] as List<string>;
ListBox1.Text = string.Join(",", myList);

Upvotes: 2

Related Questions