简体   繁体   中英

How to multiple select item in ListBox without press CTRL in Asp.Net?

I want to select multiple items in ListBox , but the browser requires the user to press CTRL to select multiple items otherwise it selects just one item.

I want to select multiple items without pressing CTRL, and I don't want to use CheckBoxList . Is there any better way of doing it? Using pure javascript, or JQuery or Codebehind.

(I already added SelectionMode="Multiple" attributes to ListBox controls)

Code:

    <asp:ListBox ID="ListBox1" runat="server" Height="210px" Width="203px" SelectionMode="Multiple">
        <asp:ListItem>1000</asp:ListItem>
        <asp:ListItem>2000</asp:ListItem>
        <asp:ListItem>4000</asp:ListItem>
        <asp:ListItem>4000</asp:ListItem>
        <asp:ListItem>5000</asp:ListItem>
        <asp:ListItem>6000</asp:ListItem>
    </asp:ListBox>

Ref: Making a standard ASP.NET listbox do multiselect without holding Ctrl

Just change your listbox to

<asp:ListBox ID="ListBox1" runat="server" Height="210px" Width="203px" SelectionMode="Multiple" onclick="ListBoxClient_SelectionChanged(this, event);">
        <asp:ListItem>1000</asp:ListItem>
        <asp:ListItem>2000</asp:ListItem>
        <asp:ListItem>4000</asp:ListItem>
        <asp:ListItem>4000</asp:ListItem>
        <asp:ListItem>5000</asp:ListItem>
        <asp:ListItem>6000</asp:ListItem>
</asp:ListBox>

And add following script in your <script> tag

<script type="text/javascript" language="javascript">
        var selectedClientPermissions = [];

        function pageLoad() {
            var ListBox1 = document.getElementById("<%= ListBox1.ClientID %>");

            for (var i = 0; i < ListBox1.length; i++) {
                selectedClientPermissions[i] = ListBox1.options[i].selected;
            }
        }

        function ListBoxClient_SelectionChanged(sender, args) {
            var scrollPosition = sender.scrollTop;

            for (var i = 0; i < sender.length; i++) {
                if (sender.options[i].selected) selectedClientPermissions[i] = !selectedClientPermissions[i];

                sender.options[i].selected = selectedClientPermissions[i] === true;
            }

            sender.scrollTop = scrollPosition;
        }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM