I want to store items to a list but everytime i press the confirm button to add one item to the list the page will refresh and reset my list. How do i stop this from happening whilst at the same time have an add button to keep adding to the list?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
else
{
slist = (List<Shopping>)ViewState["Items"];
}
}
List:
private static List<Shopping> slist;
public List<Shopping> GetShopping()
{
return slist;
}
Button Click:
slist = new List<Shopping>();
Shopping s = new Shopping();
s.Item1 = txtItem1.Text;
s.Item2 = txtItem2.Text;
s.Item3 = txtItem3.Text;
s.Item4 = txtItem3.Text;
slist.Add(s);
ViewState["Items"] = slist;
showShopping();
Method:
showShopping()
{
GridView1.DataSource = GetShopping();
GridView1.DataBind();
}
Do not store business objects in ViewState. Use the Session
private List<Shopping> ShoppingList
{
get {
var shopping = Session["Shopping"] as List<Shopping>;
if (shopping == null)
{
shopping = new List<Shopping>();
Session["Shopping"] = shopping;
}
return shopping;
}
set { Session["Shopping"] = value; }
}
Button handler
var shopping = ShoppingList;
shopping.Add(new Shopping());
...