Moving items between listboxes in example

June 12, 2008 by JavaScript   PHP   ASP.NET   Visual Basic  

Ever wanted to move items between two listboxes in (or PHP for that matter)?

Someone wanted the exact same thing on a while ago but I didn't give much thought to it, until someone at work asked me how to do it - since he wasn't able to find a viable solution on the internet.

The solution I scripted wasn't as simple as I thought, nor would have liked it to be, my feeling was that one would be able to alter the two listboxes easily using javascript and simply "harvest" the changes (from the Request variables) when its submitted to the server.

The reality however is that only items selected(or highlighted) in the listboxes, will be returned to the server, not the state of the listboxes - so we need to somehow send the state of the listboxes along with the page request.

What I did was, I wrote a javascript script, that serialized the contents of the listboxes as xml to a hiddenfield on the page - whenever you submit the form to the server, a xml string containing the state of the listboxes get sent along - which one can easily process server side (which I will show you just in a while).

function move(fromID, toID, containerID)
    var from = document.getElementById(fromID);
    var to = document.getElementById(toID);

    for (var i = 0; i < from.options.length; i++)
        if (from.options[i].selected)
            to.options.add(new Option(from.options[i].text,from.options[i].value))

    var container = document.getElementById(containerID);	
    container.value = escape("<listboxes>" + serialize(from) + serialize(to) + "</listboxes>");

function serialize(dropdown)
    var value = '<' + + '>';	
    for (var i = 0; i < dropdown.options.length; i++)
        value+= '<option><key><![CDATA[' + encodeURIComponent(dropdown.options[i].text) + ']]></key><value><![CDATA[' + encodeURIComponent(dropdown.options[i].value) + ']]></value></option>';
    value+='</' + + '>';
    return value

function unselect(listbox)

Tying it all together (javascript with some .net code), you can easily write yourself an usercontrol, like I did in my example, or create a composite control.

The .net code below is pretty straighforward, you'll noticed two publicly exposed ListBox properties (lstFrom, lstTo), giving us easy access to the listboxes.

If you really need to, you can easily add third, forth listboxes (with slight changes to the javascript code)

The PHP code is quite a bit more involved, I had to create a few classes that give similiar control of what you would expect from an ASP.NET server side control. There is a lot easier ways to do this, but I believe this is a fairly manageable approach.

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class ListPicker : System.Web.UI.UserControl
    private XmlDocument _xmlDocument = new XmlDocument();

    public ListBox fromListBox
            return lstFrom;

    public ListBox toListBox
            return lstTo;

    private void PopulateListBox(ListBox listBox)
        XmlNodeList nodes = _xmlDocument.SelectNodes("listboxes/" + listBox.ClientID + "/option");
        foreach (XmlNode node in nodes)
            listBox.Items.Add(new ListItem(HttpUtility.UrlDecode(node["key"].InnerText), HttpUtility.UrlDecode(node["value"].InnerText)));

    private void PopulateListBoxes()

    protected void Page_Load(object sender, EventArgs e)
        Page.ClientScript.RegisterClientScriptInclude("listboxjs", Page.ResolveClientUrl("~/js/listbox.js"));
        if (!IsPostBack)
            String movejs = "move('{0}','{1}','{2}')";
            String unselectjs = "unselect('{0}')";
            lstFrom.Attributes["onclick"] = String.Format(unselectjs, lstTo.ClientID);
            lstTo.Attributes["onclick"] = String.Format(unselectjs, lstFrom.ClientID);
            btnTo.Attributes["onclick"] = String.Format(movejs, lstFrom.ClientID, lstTo.ClientID, hdnDropdowns.ClientID);
            btnFrom.Attributes["onclick"] = String.Format(movejs, lstTo.ClientID, lstFrom.ClientID, hdnDropdowns.ClientID);
            if (!(String.IsNullOrEmpty(hdnDropdowns.Value)))
Imports System.Xml

Partial Class ListPicker
    Inherits System.Web.UI.UserControl

    Private _xmlDocument As New XmlDocument()

    Public ReadOnly Property fromListBox() As ListBox
            Return lstFrom
        End Get
    End Property

    Public ReadOnly Property toListBox() As ListBox
            Return lstTo
        End Get
    End Property

    Private Sub PopulateListBox(ByVal lstBox As ListBox)
        Dim nodes As XmlNodeList = _xmlDocument.SelectNodes("listboxes/" + lstBox.ClientID + "/option")
        For Each node As XmlNode In nodes
            lstBox.Items.Add(New ListItem(HttpUtility.UrlDecode(node.Item("key").InnerText), HttpUtility.UrlDecode(node.Item("value").InnerText)))
    End Sub

    Private Sub PopulateListBoxes()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Page.ClientScript.RegisterClientScriptInclude("listboxjs", Page.ResolveClientUrl("~/js/listbox.js"))

        If Not IsPostBack Then
            Dim movejs As String = "move('{0}','{1}','{2}')"
            Dim unselectjs As String = "unselect('{0}')"

            lstFrom.Attributes("onclick") = String.Format(unselectjs, lstTo.ClientID)
            lstTo.Attributes("onclick") = String.Format(unselectjs, lstFrom.ClientID)
            btnTo.Attributes("onclick") = String.Format(movejs, lstFrom.ClientID, lstTo.ClientID, hdnDropdowns.ClientID)
            btnFrom.Attributes("onclick") = String.Format(movejs, lstTo.ClientID, lstFrom.ClientID, hdnDropdowns.ClientID)
            If Not String.IsNullOrEmpty(hdnDropdowns.Value) Then
            End If
        End If
    End Sub
End Class


class listpicker extends controls
    var $lstFrom;
    var $lstTo;
    var $deserializable;

    function listpicker($id)
        $this->attributes['id'] = $id;
        $this->lstFrom = new listbox($id.'_lstFrom');
        $this->lstFrom->attributes['style'] = 'width:200px';
        $this->lstFrom->attributes['onclick'] = "unselect('".$id."_lstTo')";	
        $this->lstTo = new listbox($id.'_lstTo');
        $this->lstTo->attributes['style'] = 'width:200px';
        $this->lstTo->attributes['onclick'] = "unselect('".$id."_lstFrom')";

        if ($_REQUEST[$id.'$hdnDropdowns'])
            $this->deserializable = true;

    function render()
    $id = $this->attributes['id'];
                        <input id="btnTo" type="button" value=">>" onclick="move(\''.$id.'_lstFrom\',\''.$id.'_lstTo\',\''.$id.'_hdnDropdowns\')" />
                            <br />
                        <input id="btnFrom" type="button" value="<<" onclick="move(\''.$id.'_lstTo\',\''.$id.'_lstFrom\',\''.$id.'_hdnDropdowns\')" />
	        <input type="hidden" ID="'.$id.'_hdnDropdowns" name="'.$id.'$hdnDropdowns" />';		
    return $html;

    function xml($text) 
        $id = $this->attributes['id'];
        $parser = xml_parser_create();
        xml_parse_into_struct($parser, $text, $vals);
        $tag = "";

        for($i = 0; $i < count($vals); $i++)
                case strtoupper($id.'_lstFrom') : $tag = "lstFrom";	break;
                case strtoupper($id.'_lstTo') : $tag = "lstTo";	break;

            if (($tag) && ($vals[$i]['tag'] == "KEY"))
                $this->{$tag}->addItem($vals[$i]['value'], $vals[$i+1]['value']);					


Related Downloads

Moving items between listboxes

Leave a Comment

Getting and updating data from the list August 7, 2013 by Anonymous

Dear, First, thank for your interesting codes. I used the codes to load data from database to the first list and I need your help to store items of the second list to database. How to get these values, I tried with _POST[] but I can't refer to the name of the second one. I look forward to your reply. Regard, Duy

August 2, 2013 by Maya

Hi again, I used: include "includes/listpicker.php"; $picker = new listpicker("picker"); print_r($picker->lstTo); and I got Again Picker = listbox Object ( [items] => Array ( [St. Lucy C.S.] => STLUC [Birchbank P.S.] => BBANK [Arnott Charlton P.S.] => ARNCH [Kingswood Drive P.S.] => KINWD [Treeline P.S.] => TREEL ) [attributes] => Array ( [id] => picker_lstTo [multiple] => multiple [style] => width:200px [onclick] => unselect('picker_lstFrom') ) ) : What I need is to take only the values (STLUC, BBANK, ARNCH, KINWD, TREEL) to insert them in database. I am new in PHP and I don't know how get this values and keep them in variables. thank you Maya

retrieve values of selected August 2, 2013 by Maya

Hi, Thank you for sharing the code, it is very useful for me. Please can anybody tell me how can I get the values of the selected items? In which variables are they stored? I need these variables to save the selected items in database. Thank You in advance Maya

Can you modify the code so that only one element can be transferred. February 28, 2013 by Rohit

Hi Christoff Truter, Your code is great but I have a requirement that would allow a user only to select a single item from listbox(from) and transfer it to listbox(to). Rest all items from listbox(from) cannot be transferred to listbox(to). i.e only one item can be transferred from listbox(from) to listbox(to).

many to one October 17, 2012 by Anonymous

Hi Christoff Truter, I already downloaded your source code. That's very helpful. Thank you so much, Now I want to do some revise about your code. I want in left there are 3 or more listboxs, in right side only one listbox. Item form each listboxs can move to the right one. Can you give me a hint how to do that change? Thank you again

Thanks: Latest Source Code May 8, 2012 by Iva

Christoff, thanks a lot for your care. It's great. Iva

Problem with some characters at ListPicker April 25, 2012 by Iva

dear Christoff, thanks a lot for your code. It's very useful for me. So I found the problem when I use for example Czech characters (á,,&#269; and every others) - when page is loaded (ASP.Net VB), everything it's OK, when I move some items between source and destinations listboxes in listpicker and click to proceed button, this source and destination listboxes include bad characters - I can send screenshot if you would like. The rest lispickers, where I haven't moved any item, are OK. Can you help me? I use encoding utf-8 at ASPX pages and MS SQL database too. Thank you.

RE: asp_tags March 27, 2012 by Christoff Truter

Hi Aisha Thanks, I will be sure to update the source code, the <?= tag only works if the asp_tags directive are enabled. It hinders portability a bit (like many other PHP directives)

March 27, 2012 by Aisha

Some users might have trouble running the site using eclipse Change <?=$picker->render(); ?> to <?php echo $picker->render(); ?> the php tags were not correct and the echo function had to be called.. Hope this helps.. Thanks for the great script sweetie

March 27, 2012 by Anonymous

I cant thank you enough for posting this

Latest Posts

Dependency Injection using Ninject and PostSharp

April 26, 2016

Aspect Orientated Programming (AOP) - A Brief look at PostSharp

April 15, 2016

How to become a better programmer.

April 5, 2016

JavaScript Fundamentals - Hoisting

March 22, 2016

Quick and dirty look at ECMAScript 6

March 17, 2016

JavaScript Promises

March 9, 2016

CSS Combinators

March 7, 2016

Shingles Awareness

March 4, 2016

Google Analytics : Measurement Protocol

February 24, 2016

Interesting JavaScript - SQLite (sql.js)

February 18, 2016

Most Commented on Posts

Moving items between listboxes in example

Move items between two listboxes in, VB.NET) and PHP
June 12, 2008

Simple WYSIWYG Editor

Creating a WYSIWYG textbox for your website is actually quite simple.
February 1, 2007

C# YouTube : Google API

Post on how to integrate with YouTube using the Google Data API
March 12, 2011

Populate a TreeView Control C#

Populate a TreeView control in a windows application.
August 27, 2009

ASP.NET(C#) : Autocomplete TextBox - Part 1 (From Scratch)

Part one of how to create an autocomplete textbox using ASP.NET(C#)
March 27, 2011

Angular   Architecture   ASP.NET   Astronomy   Breaking News   C#   C++   Coding Horrors   Comedy   Cross Browser   CSS   Design Patterns   ES6   Google API   IIS   Integration   JavaScript   Jquery Mobile   Love and War   Microsoft Office   Ninject   Personal   PHP   PostSharp   SEO   South Africa   SQL   Threading   TypeScript   Visual Basic   XML