动态DropDownList索引事件不会触发

时间:2015-05-03 07:26:53

标签: c# asp.net drop-down-menu

在ASP.Net应用程序中,我有一个用户可以购买商品的页面。为此,他们使用两个DropDownLists:一个用于查找itemID,第二个用于选择他们想要购买的商品数量,名为Amount和PurchasedItemIDs。每个项目都有单独的草药/宝石价格。

我希望更改一个名为TotalPrice的Label,以便在用户更改所选索引时使用草药和宝石的总价格。

我做了一个活动:

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; 
    }

我编辑了下拉列表:

<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.

我做错了什么?

1 个答案:

答案 0 :(得分:2)

添加AutoPostBack =&#34; true&#34;到您的下拉列表控件:

<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>