2 Listboxes – Moving Items From One to Another

Many times we need to create a page and choose items from a listbox, moving them to the other one. This code sample shows how to not only copy the items over to the other one, but remove them from listbox1 also. For simplicity’s sake, the items shown here, are manually added in the Page_Load event.

Just copy this code straight from the page into a new file, save it with the ASPX extension and try it out!

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.0">
<title>Untitled</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
If Not Page.IsPostBack Then
Dim intFirst As Integer
For intFirst = 1 To 10
ListBox1.Items.Add("Item " & intFirst)
Next
End If
End Sub

Sub button1_click(Source as Object, E as EventArgs)
Dim li As ListItem
For Each li In ListBox1.Items
If li.Selected = True Then
ListBox2.Items.Add(li.Text)
End If
Next

Dim counter As Integer
For counter = (ListBox1.Items.Count – 1) To 0 Step -1
If ListBox1.Items(counter).Selected = True Then
ListBox1.Items.RemoveAt(counter)
End If
Next
End Sub

Sub button2_click(Source as Object, E as EventArgs)
Dim counter As Integer
Dim li As ListItem

For Each li In ListBox2.Items
If li.Selected = True Then
ListBox1.Items.Add(li.Text)
End If
Next

For counter = (ListBox2.Items.Count – 1) To 0 Step -1
If ListBox2.Items(counter).Selected = True Then
ListBox2.Items.RemoveAt(counter)
End If
Next
End Sub
</script>
</head>
<body>
<div align="center"><Form id="form1" runat="server">
<table cellpadding="2" cellspacing="2" border=0>
<tr>
<td align="center" valign="top"><asp:ListBox id="ListBox1" width="125px" height="175" SelectionMode="Multiple" runat="server" /></td>
<td align="center" valign="center"><asp:Button id="button1" width="88px" height="26" Text="Add >>" onclick="button1_click" runat="server" /><br>
<asp:Button id="button2" Text="<< Remove" onclick="button2_click" width="88px" height="26" runat="server" />
</td>
<td align="center" valign="top"><asp:ListBox id="Listbox2" width="125px" height="175" SelectionMode="Multiple" runat="server" /></td>
</tr>
</table>
</Form></div>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>