Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain generic list between postbacks

Here is what is in my code-behind:

List<Event> events = new List<Event>();

protected void Page_Load(object sender, EventArgs e)
{

}

protected void AddEvent_Click(object sender, EventArgs e)
{
    Event ev = new Event();

    ev.Name = txtName.Text;

    events.Add(ev);
}

I want to add an item to the list every time the Add button is clicked, but the list is reset after every postback. How can I keep the data in the list between postbacks?

like image 211
Steven Avatar asked Sep 14 '10 15:09

Steven


3 Answers

I often use a technique such as this, although keep in mind this can cause your viewstate (as rendered to the browser) to grow rather large:

public List<Event> Events 
{
  get { return (List<Event>)ViewState["EventsList"]; }
  set { ViewState["EventsList"] = value; }
}

Then when you want to use the list you would do something like this:

public void AddToList()
{
    List<Event> events = Events; // Get it out of the viewstate
    ... Add/Remove items here ...
    Events = events; // Add the updated list back into the viewstate
}

Also note that your Event class will need to be serializable, but that's usually as simple as adding the [Serializable] attribute to the class (unless its a really complex class).

like image 120
CodingGorilla Avatar answered Oct 06 '22 12:10

CodingGorilla


Save list into session or viewstate.

protected void AddEvent_Click(object sender, EventArgs e)
{
    Event ev = new Event();

    ev.Name = txtName.Text;
    if(Session["events"] == null)
    {
      Session["events"] = new List<Event>();
    }
    var events = (List<Event>)Session["events"];
    events.Add(ev);
}
like image 29
Alex Reitbort Avatar answered Oct 06 '22 12:10

Alex Reitbort


You'll need to maintain the list yourself somehow. You can stuff it into ViewState, push it to the database, store it in the Session, put it into a HiddenField on the page...

like image 30
bdukes Avatar answered Oct 06 '22 13:10

bdukes