Why event not fired when I change selection on DropDownList?

时光总嘲笑我的痴心妄想 提交于 2021-02-16 20:42:10

问题


I have this asp net drp box:

<asp:DropDownList ID="ddlLayersList"
        runat="server"
        BackColor="#FFFFC0"
        CssClass="form-control fullwidth" OnTextChanged="ddlLayersList_SelectedIndexChanged" >
</asp:DropDownList>

Here is how I fill the drop box:

private void SetLayers(Dictionary<string, string> layers)
{
    ddlLayersList.DataSource = layers;
    ddlLayersList.DataValueField = "Key";
    ddlLayersList.DataTextField = "Value";
    ddlLayersList.DataBind();
    ddlLayersList.Items.Insert(0, "-Select Item-");
}

And here is code behind event:

protected void ddlLayersList_SelectedIndexChanged(object sender, EventArgs e)
{
}       

When I select item from drop box the event not fired. Any idea why event not fired when I change selection on DropDownList?


回答1:


You need to set the AutoPostBack property to True.

<asp:DropDownList ID="ddlLayersList" AutoPostBack="True">

The value of this property:

true if a postback to the server automatically occurs whenever the user changes the selection of the list; otherwise, false. The default is false

Also you need to set the OnSelectedIndexChanged event instead of OnTextChanged:

<asp:DropDownList ID="ddlLayersList" 
       AutoPostBack="true" runat="server" 
       OnSelectedIndexChanged="ddlLayersList_SelectedIndexChanged">




回答2:


Besides on setting AutoPostBack="true" to enable automatic postback, also set OnSelectedIndexChanged event handler instead of OnTextChanged (note that both of them are not the same event):

<asp:DropDownList ID="ddlLayersList"
           runat="server"
           BackColor="#FFFFC0"
           AutoPostBack="true"
           CssClass="form-control fullwidth" 
           OnSelectedIndexChanged="ddlLayersList_SelectedIndexChanged">
</asp:DropDownList>


来源:https://stackoverflow.com/questions/53041100/why-event-not-fired-when-i-change-selection-on-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!