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

I've always hated that users of a standard ASP.NET listbox control must hold ctrl to select multiple items. It's just a recipe for bad/incomplete data input. So, I set out to see if I could make the listbox do multiselect without holding the ctrl key. I know that there are third party controls out there that accomplish this more elegantly, but I wanted to see if it was possible with a standard control. I managed to get it going with some javascript help.

First, I defined my listbox & gave it an onclick event to fire a javascript method:


Second, I created the javascript method (the last one below) to loop through the listbox elements, select all of the items previously selected, and toggle the one the user clicked.
//This array holds the "selected" state of each listbox item
var selectedClientPermissions = [];

//Because I'm working with a databound listbox, I grab the selected values
//on page load & put them in the array.
function pageLoad()
{
    var ListBoxClient = document.getElementById("<%= ListBoxClient.ClientID %>");
    
    for (var i = 0; i < ListBoxClient.length; i++)
    {
        selectedClientPermissions[i] = ListBoxClient.options[i].selected;
    }
}

function ListBoxClient_SelectionChanged(sender, args)
{
    var scrollPosition = sender.scrollTop;
    
    for (var i = 0; i < sender.length; i++)
    {
        //if this is the one clicked by the user, toggle it's state
        if (sender.options[i].selected) selectedClientPermissions[i] = !selectedClientPermissions[i];
        
        //Assign saved selections from array
        sender.options[i].selected = selectedClientPermissions[i] === true;
    }
    
    sender.scrollTop = scrollPosition;
}

So, in this way I was able to get the desired functionality with a standard listbox. Is it a hack? absolutely, but it works as a proof of concept.

Comments

Popular posts from this blog

Fixing Conan Lock Issues

Dynamic Object Oriented programming in ArchestrA

Initialize With Care