tahasozgen
tahasozgen

Reputation: 491

ASP.NET DropDownList SelectedIndexChanged event not working

I have a basic drop down list. Upon selection of an item in the list, I expect to update the label with the choice of drop down list. But my code section does not show any update. Here is the code:

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>

What is wrong with it?

Upvotes: 0

Views: 2777

Answers (2)

Jaqen H&#39;ghar
Jaqen H&#39;ghar

Reputation: 16804

Add AutoPostBack="true" to the <asp:DropDownList>:

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

By default <asp:DropDownList> do not post back changes to the server.

Upvotes: 1

simpleman
simpleman

Reputation: 21

You might also want to set the DataValueField for your dropdownlist:

benimDropDownList.DataValueField = "Key";

Upvotes: 1

Related Questions