我是asp新的品牌,所以我認爲這個答案應該是一個簡單的方法,但我無法弄清楚我做錯了什麼。這是一個非常簡單的購物車練習,我正在學習ASP。我創建了會話,添加了一些內容,然後在結帳頁面上可以逐個刪除購物車中的物品。如果我點擊刪除,該項目將從列表框中刪除,但不會從會話中刪除。我知道它在會話中仍然存在,因爲如果我點擊鏈接到購物頁面,購物頁面上的列表框將填充我認爲已刪除的項目。從會話索引(ASP)中刪除字典條目
我試着去除它兩種不同的方式,我不知道爲什麼它不工作。
注意:字典鍵是用於填充列表框的產品的實際名稱。值條目是我現在沒有實際使用的productID#。購物頁面上的列表框正在填充來自sqlsource的數據。 SelectedItem.Text =產品名稱(顯示內容)和SelectedValue = productID(未使用)。
非常感謝您的幫助
//Default (shopping) page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create a new collection for the session indexer
ArrayList cart = (ArrayList)Session["scart"];
//Need to initialize a new object in case it's null
if (cart == null)
{
cart = new ArrayList();
Session["scart"] = cart;
}
//Show the shopping car listbox if there are items in it and the
//user returned from the checkout page
else pnlItems.Visible = true;
foreach (DictionaryEntry item in cart)
{
lbItems.Items.Add((string)item.Key);
}
}
//Show the shipping cart listbox containing the items the user just added
if (IsPostBack) pnlItems.Visible = true;
}
private void add_to_cart(string item, int value)
{
//Method to add the selected item to the collection/session indexer
ArrayList cart = (ArrayList)Session["scart"];
cart.Add(new DictionaryEntry(item, value));
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
//Method to send the selected item to the add_to_cart method
string item = ddlProducts.SelectedItem.Text;
lbItems.Items.Add(item);
int value = int.Parse(ddlProducts.SelectedValue);
add_to_cart(item, value);
}
protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnCheckOut_Click(object sender, EventArgs e)
{
//Send the user to the checkout page when the button is clicked
Response.Redirect("checkout.aspx", true);
}
}
//CheckoutPage:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate the shopping cart on the checkout page with the items in the collection
ArrayList cart = (ArrayList)Session["scart"];
foreach (DictionaryEntry item in cart)
{
lbCheckOut.Items.Add((string)item.Key);
}
}
}
protected void btnKillOrder_Click(object sender, EventArgs e)
{
//Kills the order by ending the session, then returns the user to the shopping page.
Session.Clear();
Response.Redirect("Default.aspx", true);
}
protected void btnRemove_Click(object sender, EventArgs e)
{
//Removes the selected item from the shopping cart listbox and the session indexer
ArrayList cart = (ArrayList)Session["scart"];
cart.Remove(lbCheckOut.SelectedItem.Text);
lbCheckOut.Items.Remove(lbCheckOut.SelectedItem.Text);
Session["scart"] = cart;
//Session.Remove(lbCheckOut.SelectedItem.Text);
}
}
謝謝,這個工作!我曾嘗試類似於此前的東西,但在foreach語句中出現枚舉器錯誤。不知道如何進行調試,我放棄了並嘗試了上面提到的方法。無論如何,謝謝! – 2010-11-26 19:19:23