Search code examples
asp.netdrop-down-menuautopostback

Stop autopostback on keyboard input for dropdownlist


Is there any way do delay the autopostback on a dropdownlist until the list actually loses focus? I want to accept input from the keyboard without the page posting back after every keystroke. For example, take this code:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem >Test1</asp:ListItem>
<asp:ListItem >Tst1</asp:ListItem>
<asp:ListItem >twotest</asp:ListItem>
</asp:DropDownList>

Say I want to select twotest. I tab to the ddl and input 'tw' into my keyboard. However, as soon as the 't' is entered, the page automatically posts back, while the 'w' input is lost. Resetting focus doesn't really help any as then the ddl thinks that 'w' is the first input. Any help would be appreciated.


Solution

  • It seems impossible. You must remove AutoPostBack="true" and try another way to perform postback. Consider below solution:

    when dropdown ddlCountry changed, the function ddlCountry_changed is called that trigger btnLoad click to perform postback. The button btnLoad is put inside an update panel so the page is not reload and you still have focus on the dropdown.

    <script type="text/javascript">
        function ddlCountry_changed() {
            document.getElementById('<%= btnLoad.ClientID %>').click();
        }
    </script>
    
    Country:
    <asp:DropDownList ID="ddlCountry" runat="server" onchange="ddlCountry_changed();">
        <asp:ListItem Text="Vietnam" Value="1"></asp:ListItem>
        <asp:ListItem Text="United State" Value="2"></asp:ListItem>
    </asp:DropDownList>
    
    <asp:UpdatePanel ID="updatePanel" runat="server">
        <ContentTemplate>
            <asp:Button ID="btnLoad" style="display: none" runat="server" OnClick="btnLoad_OnClick" />
        </ContentTemplate>
    </asp:UpdatePanel>