ASP.NET DropDownList SelectedIndexChanged事件无法正常工作

时间:2016-09-11 09:08:21

标签: asp.net webforms

我有一个基本的下拉列表。在选择列表中的项目后,我希望通过选择下拉列表来更新标签。但我的代码部分没有显示任何更新。这是代码:

MainPage.aspx.cs:

protected void Page_Load(Object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        // Use integers to index each item. Each item is a string.
        Dictionary<int, string> fruit = new Dictionary<int, string>();
        fruit.Add(1, "Kiwi");
        fruit.Add(2, "Pear");
        fruit.Add(3, "Mango");
        fruit.Add(4, "Blueberry");
        fruit.Add(5, "Apricot");
        fruit.Add(6, "Banana");
        fruit.Add(7, "Peach");
        fruit.Add(8, "Plum");
        // Define the binding for the list controls.
        benimDropDownList.DataSource = fruit;
        // Choose what you want to display in the list.
        benimDropDownList.DataTextField = "Value";
        // Activate the binding.
        this.DataBind();
    }
}

protected void benimDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    lblSonuc.Text = "You picked: " + benimDropDownList.SelectedItem.Text;
    lblSonuc.Text += " which has the key: " + benimDropDownList.SelectedItem.Value;
}

MainPage.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="benimDropDownList" runat="server" OnSelectedIndexChanged="benimDropDownList_SelectedIndexChanged">
        </asp:DropDownList>
        <asp:Label ID="lblSonuc" runat="server"></asp:Label>  
    </div>
    </form>
</body>
</html>

它出了什么问题?

2 个答案:

答案 0 :(得分:1)

AutoPostBack="true"添加到<asp:DropDownList>

<asp:DropDownList ID="benimDropDownList" runat="server" 
    OnSelectedIndexChanged="benimDropDownList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>

默认情况下<asp:DropDownList>不会将更改回发给服务器。

答案 1 :(得分:1)

您可能还想为下拉列表设置DataValueField:

benimDropDownList.DataValueField = "Key";