Maintaining a common list between postbacks

Here is what is in my code:

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 each time I click the Add button, but the list is reset after every postback. How to save data in a list between postbacks?

+5
source share
4 answers

I often use this technique, although keep in mind that this can cause your viewstate (as shown in the browser) to become quite large:

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

Then, when you want to use a list, you should 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
}

, Event , , [Serializable] ( ).

+8

- . ViewState, , , HiddenField ...

+1

Save the list in a session or in a view.

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);
}
+1
source

Thanks CodingGorilla, this solved my problem. But I have to add one more thing for beginners.

List<Event> events = Events; // Get it out of the viewstate
**You should check whether events is null** 
Events = events; // Add the updated list back into the viewstate
0
source

All Articles