【问题标题】:ASP.NET DropDownList SelectedIndexChanged event not workingASP.NET DropDownList SelectedIndexChanged 事件不起作用
【发布时间】:2016-09-11 09:08:20
【问题描述】:

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

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>

这有什么问题?

【问题讨论】:

    标签: asp.net webforms


    【解决方案1】:

    AutoPostBack="true" 添加到&lt;asp:DropDownList&gt;

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

    默认情况下&lt;asp:DropDownList&gt; 不会将更改回发到服务器。

    【讨论】:

    • 哦我忘了。
    【解决方案2】:

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

    benimDropDownList.DataValueField = "Key";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-08
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多