>I have a form that I using to add details to an array, but I need to
> continue to add these details to my array on multiple postbacks....how
> can I do this? Do I need to use a Session object instead?
You need to preserve the array across postbacks using one of the various
mechanisms available for persisting state. One of them is the Session
object, as you mentioned, but there are other mechanisms that may be useful
depending on the circumstances, such as the ViewState.
The Session is stored in memory at the server (unless you send it to a
StateServer or a Sql Database), which can be inconvenient if the server has
lots of users because it will take up lots of memory. It also requires
cookies to be enabed in the browser, unless you enable cookieless sessions.
The ViewState is kept in a hidden field in your page, so it will be sent
over the line on each postback and each reply. This may be inconvenient if
your bandwidth is limited. It also requires that the objects that you store
in the array be Serializable.
So how do you do this? In your Page_Load method, you read your data from
the Session (or ViewState) and store it into your array, which you will have
declared as as class variable. In your Button_Click event (whatever you use
to submit the details to add), you add the data to your array and store the
array back into the Session or ViewState. That's all. It should work.
Mike P - 14 Oct 2007 20:26 GMT
Alberto,
What is wrong with my code here? I need to make the ArrayList not equal
to null on the first page load so that I can add to it on the button
click.
ArrayList orders = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
orders = (ArrayList)Session["Order"];
}
else
{
orders = new ArrayList();
}
}
Alberto Poblacion - 14 Oct 2007 21:10 GMT
> What is wrong with my code here? I need to make the ArrayList not equal
> to null on the first page load so that I can add to it on the button
[quoted text clipped - 13 lines]
> }
> }
The wrong part is that the first time (when PostBack is false) you don't
store "orders" in Session, so after the first PostBack Session["order"] is
null.
Another thing is that the "new" in the declaration of the variable is
superfluous, since you are always going to initialize it during Page_Load.
ArrayList orders;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
orders = (ArrayList)Session["Order"];
}
else
{
orders = new ArrayList();
Session["Order"]=orders;
}
}
Mike P - 14 Oct 2007 21:23 GMT
Many thanks...I managed to figure this one out shortly after posting but
thanks for replying anyway!