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?
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).
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);
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With