Within an asp.net web form I would like to add values back to a .net object type that I have created on the server within my code behind I have the following:
protected void Page_Load (object sender, EventArgs e)
{
if (!IsPostBack)
{
myArrayList.Add("Value 1");
myArrayList.Add("Value 2");
myBox.DataSource = myArrayList;
}
myBox.DataBind();
myTime.Text = DateTime.Now.ToString();
}
protected void btnAddText_Click (object sender, EventArgs e)
{
myArrayList.Add(mytext.Text.ToString());
myBox.DataSource = myArrayList;
myBox.DataBind();
}
public ArrayList myArrayList = new ArrayList();
What I would like to do is take values entered into the textbox on the client and when the button is clicked add/append them to the array. Currently, (as expected) the array is reset to null once the button is clicked. If I don’t use the isPostBack it only retains the last value, once again as expected. I have asp:updatepanels in place in the Ui with conditional updates and I realize that the asp.net page life-cycle still fires on the postback (causing Init, Load, pre-render and unload).
My asp.net is rusty but for scenarios like this is the best (only) approach to use Session State and store the array in the session for manipulation or am I missing something?
Thanks for any guidance,
After some more research I decided to go the route of using Session State. There are a number of options for state management but session was the most straight forward and extensible for what I wanted to do.
For any interested here is a working solution showing a list array being used as a session variable.
Within a document I setup a basic field, button and listbox for testing:
Then within the code behind I setup the following:
//quick example of session state where we contribute to the session object from the Ui
//similar to a shoping cart example
// You could use any object or type I just used an array as it was fast
When working with session variables it may also be a good idea to test for null session variable (to see if the variable exits). In some instances failure to do so could result in a null reference exception being thrown if you attempt to add to the session before it is created.
Hope this helps