Internet Explorer 5.5Internet Explorer 7Internet Explorer 6.0IEVisual Studio .NET 2002.NET 1.0Visual Studio .NET 2003Windows 2003WebForms.NET 1.1.NET 3.0Visual Studio 2005Windows 2000Windows XP.NET 2.0IntermediateDevVisual StudioJavascriptWindows.NETASP.NET
Moving Items from one Listbox to another.






3.48/5 (13 votes)
May 12, 2007

131328
This Article explains how to move Items between two listbox
Introduction
This Article is usefull to move the list items between 2 listbox or combo or dropdown, it will also give an alert message if no items of the listbox are selected.
Background
This code can be used in any web applications, in the javascript part.
Using the code
Assumptions:
The name of Buttons are assumed to be btnMoveRight and btnMoveLeft
The name of the ListBox are assumed to be ListBox1 and ListBox2
Code for the javascript function: function fnMoveItems(lstbxFrom,lstbxTo) { var varFromBox = document.all(lstbxFrom); var varToBox = document.all(lstbxTo); if ((varFromBox != null) && (varToBox != null)) { if(varFromBox.length < 1) { alert('There are no items in the source ListBox'); return false; } if(varFromBox.options.selectedIndex == -1) // when no Item is selected the index will be -1 { alert('Please select an Item to move'); return false; } while ( varFromBox.options.selectedIndex >= 0 ) { var newOption = new Option(); // Create a new instance of ListItem newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text; newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value; varToBox.options[varToBox.length] = newOption; //Append the item in Target Listbox varFromBox.remove(varFromBox.options.selectedIndex); //Remove the item from Source Listbox } } return false; } code for calling the javascript function: There are 2 methods of calling the javascript code, they are as under. 1. Add this code in the pageload btnMoveRight.Attributes.Add("onclick","return fnMoveItems('ListBox1','ListBox2')"); btnMoveLeft.Attributes.Add("onclick","return fnMoveItems('ListBox2','ListBox1')"); 2. Add this code in the HTML <input type = "button" id = "btnMoveRight" onclick = "fnMoveItems('ListBox1','ListBox2')"> <input type = "button" id = "btnMoveLeft" onclick = "fnMoveItems('ListBox2','ListBox1'">
Points of Interest
Let me know if you have any queries.
History
New Article on AJAX to be added shortly. :-)