Autopostback resetting my list
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 = txtIt开发者_如何学运维em1.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();
}
Stop building/binding the list on your page load without checking Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// bind / load lists and controls here
}
else
{
//this is a post back, don't reload everything
}
}
Edit *
Never do this if you ever want to support more then 1 shopper at a time.
private static List<Shopping> slist;
The users will end up writing over each others lists, then displaying the wrong one constantly. Remove the 'static' modifier.
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());
...
Been awhile since I have done WebForms, but it looks like you are assigning multiple items, but only one "Shopping" on the button click event then calling:
showShopping()
{
GridView1.DataSource = GetShopping();
GridView1.DataBind();
}
Double check your GridView1 binding if you want the items to be displayed versus the Shopping object that you are binding to.
精彩评论