2015-05-03 23 views
0

在ASP.Net應用程序中,我有一個用戶可以購買項目的頁面。爲此,他們使用兩個DropDownLists:一個找到他們的itemID,第二個選擇他們想要購買的物品的數量,名爲Amount和PurchasedItemIDs。每件商品都有獨立的Herbs/Gems價格。動態DropDownList索引事件不會觸發

我想更改一個名爲TotalPrice的標籤,以便在用戶更改所選索引時計算草藥和寶石的總價。

我做了一個事件:

protected void Price_Changed_Event(object sender, EventArgs e) 
    { 
     int HerbPrice = -1; 
     int GemPrice = -1; 
     int AmountPurchased = int.Parse(Amount.SelectedValue); 
     //Code to get the price out of the items. If it's relevant, ask for it. 
     foreach (shopItem t in Items) 
     { 
      if (t.ID == int.Parse(PurchaseItemIDs.SelectedValue)) 
      { 
       HerbPrice = t.herbCost*AmountPurchased; 
       GemPrice = t.gemCost * AmountPurchased; 
      } 
     } 
     if (HerbPrice == -1 || GemPrice == -1) 
      throw new Exception("ItemID not found."); 
     else 
      TotalPrice.Text = "Herbs: "+ HerbPrice + ", Gems: " + GemPrice; 
    } 

我editted的dropdownlists:

<asp:DropDownList ID="PurchaseItemIDs" runat="server" Width="120px" 
    BackColor="#F6F1DB" ForeColor="#7d6754" Font-Names="Andalus" CssClass="ddl" 
    onselectedindexchanged="Price_Changed_Event" 
    ontextchanged="Price_Changed_Event"> 
</asp:DropDownList> 
<asp:DropDownList ID="Amount" runat="server" Width="120px" BackColor="#F6F1DB" 
    ForeColor="#7d6754" Font-Names="Andalus" CssClass="ddl" 
    onselectedindexchanged="Price_Changed_Event" 
    ontextchanged="Price_Changed_Event"> 
</asp:DropDownList> 

儘管這樣,當我改變我想購買的物品的數量,標籤的文本根本不會改變默認值。我在事件開始時設置了一個斷點 - 它沒有被觸發。

編輯: 頁面加載內容:

if (!Page.IsPostBack) 
      { 
       for (int i = 1; i <= 100; i++) 
       { 
        ListItem t = new ListItem(); 
        t.Value = "" + i; 
        t.Text = "" + i; 
        Amount.Items.Add(t); 
       } 
       foreach (int id in from item in getItemsForUser(((User)Session["User"]).Username) select item.ID) 
       { 
        ListItem itm = new ListItem(); 
        itm.Text = "" + id; 
        itm.Value = "" + id; 
        PurchaseItemIDs.Items.Add(itm); 
       } 
       TotalPrice.Text = "Pick an item and an amount to see the price."; 
      } 
      //irrelevant stuff. 

我在做什麼錯?

+0

我能看看你的Page_Load代碼? –

回答

2

添加的AutoPostBack = 「true」 將您的下拉列表控件:

<asp:DropDownList ID="PurchaseItemIDs" AutoPostBack="true" runat="server" Width="120px" 
BackColor="#F6F1DB" ForeColor="#7d6754" Font-Names="Andalus" CssClass="ddl" 
onselectedindexchanged="Price_Changed_Event" 
ontextchanged="Price_Changed_Event"> 
</asp:DropDownList> 

<asp:DropDownList ID="Amount" AutoPostBack="true" runat="server" Width="120px" BackColor="#F6F1DB" 
ForeColor="#7d6754" Font-Names="Andalus" CssClass="ddl" 
onselectedindexchanged="Price_Changed_Event" 
ontextchanged="Price_Changed_Event"> 
</asp:DropDownList> 
+0

我已經改變了代碼來適應這個(編輯問題) - 但我得到了同樣的錯誤。 –

+0

它甚至沒有進入事件,更不用說執行第一個foreach。第一行是一個整數聲明 - 「int HerbPrice = -1;'。我在那裏設置了一個斷點,並且不會被觸發,無論我做什麼:/ –