2015-05-03 27 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;'。我在那里设置了一个断点,并且不会被触发,无论我做什么:/ –