views:

40

answers:

3

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?

+5  A: 

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).

Coding Gorilla
You do not have to assign events list back to the Events property, you working with references. It is the same list.
Alex Reitbort
@Alex Reibort: Actually you do, in the getter you're de-serializing the instance of the list out of the view state, in the setter you are serializing the instance back into the view state. The instance in code is the same, but that disappears between post backs, you need to refresh the view state after it's changed.
Coding Gorilla
No you do not. ViewState holds deserializes it's contents way before you ask for the list, so it hold reference to the list when you access it, you get back the reference, usi it to update the instance and it will be saved into viewstate automatically. Just test it.
Alex Reitbort
+1  A: 

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...

bdukes
+1  A: 

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);
}
Alex Reitbort