0
ArrayList aList = new ArrayList();
protected void Button1_Click(object sender, EventArgs e)
{
    aList.Add(DropDownList1.SelectedValue);
    ListBox1.DataSource = aList;
    ListBox1.DataBind();
}

This above code only binding the last inserted data into the array list.

The previously added data in the list is not displayed.

How to keep the items in the list being showed?

2
  • 2
    Because all objects in ASP.NET are disposed at the end of the page's lifecycle after the page was rendered as HTML and sent to the client. You have to re-create the list(i'd strongly recomment to use List<T> instead of ArrayList). Commented Feb 2, 2015 at 14:10
  • agreed, prefer a generic List<T> to ArrayList. Commented Feb 2, 2015 at 14:14

1 Answer 1

2

The list is recreated every time you post a request to the web page, so it isn't persistent.

You have a few options to save this persistently:

  • A database;
  • The Session object;
  • The ViewState object;
  • Some others, all for their specific purpose.

For example using Session:

protected void Button1_Click(object sender, EventArgs e)
{
    ArrayList aList = (ArrayList)this.Session["someParameter"];

    if (aList == null)
    {
         this.Session["someParameter"] = aList = new ArrayList();
    }

    aList.Add(DropDownList1.SelectedValue);
    ListBox1.DataSource = aList;
    ListBox1.DataBind();
}

Also, please don't use ArrayList any more, but the generic List<T>.

Sign up to request clarification or add additional context in comments.

2 Comments

and another one: Cookies!
Note that the list is now shared across the entire session, for all pages. If you don't want that, use another storage mechanism, like ViewState.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.