Jake Cube Jake Cube - 1 month ago 21
C# Question

C# Generic to Session

I been trying to use generic to store data in session.
It will have 2 page and 1 class name person to process the information.

Page 1 default page would allow user to input name and select gender and date.
I'm trying to store the submitted to generic & session to bring to 2nd page display all submitted user data.

DefaultPage

public partial class _Default : Page
{
Person p;
List<Person> Test;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Test = new List<Person>();
Session["carrytonext"] = Test;
}
}

protected void Button1_Click(object sender, EventArgs e)
{
Person p = new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate);
Label1.Text = p.PrintPerson();
Test = (List<Person>)Session["carrytonext"];
Test.Add(new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate));

}
}


Here is my class:

public class Person
{
public string name;
private string gender;
private DateTime dob;

public string Name
{
get
{return name;}

set
{name = value;}
}

public string Gender
{
get
{return gender;}

set
{gender = value;}
}

public DateTime Dob
{
get
{return dob;}

set
{dob = value;}
}

public Person(string name, string gender, DateTime dob)
{
this.name = name;
this.gender = gender;
this.dob = dob;
}

public string PrintPerson()
{
string s;
s = "Hello, my name is " + name + ". I'm " + gender + ". My DOB is " + dob.ToShortDateString() + "\n\n";
return s;
}
}


On my 2nd page:

protected void Page_Load(object sender, EventArgs e)
{
foreach (var inputstring in Test)
{
ListBox1.Items.Add(inputstring + "");
}
}

Answer

You must set session from test list again:

page 1

protected void Button1_Click(object sender, EventArgs e)
{
   Person p = new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate);
    Label1.Text = p.PrintPerson();
    Test = (List<Person>)Session["carrytonext"];
    Test.Add(new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate));
    // Add this line to your code
    Session["carrytonext"] = Test;       
}

page 2

protected void Page_Load(object sender, EventArgs e)
{
    List<Person> test = (List<Person>)Session["carrytonext"];  
    foreach (var inputstring in Test)
    {
        // change here
        ListBox1.Items.Add(inputstring.PrintPerson()+" ");
    }
}