Home
Manage Your Code
Snippet: Adding and removing items between ListBoxes (C#)
Title: Adding and removing items between ListBoxes Language: C#
Description: One function for adding items, and one for removing items. Just add the functions in your code and call them with the name of the listbox as parameter. Views: 356
Author: Snorre Gartland Date Added: 10/5/2007
Copy Code  
1        /// <summary>
2        /// Adding selected item from one listbox to another.
3        /// If listBoxTarget already has the value selected in listBoxSource, it will not be added.
4        ///
5        /// Example how to call:
6        /// AddSelectedItem(listBox1, listBox2);
7        /// </summary>
8        /// <param name="listBoxSource"></param>
9        /// <param name="listBoxTarget"></param>
10        private static void AddSelectedItem(ListBox listBoxSource, ListBox listBoxTarget)
11        {
12            if (listBoxSource.SelectedIndex != -1 && !listBoxTarget.Items.Contains(listBoxSource.SelectedItem))
13            {
14                listBoxTarget.Items.Add(listBoxSource.SelectedItem);
15            }
16        }
17
18
19        /// <summary>
20        /// Removes the selected item from the given listbox.
21        /// 
22        /// Example how to call:
23        /// RemoveSelectedItem(listBox2);
24        /// </summary>
25        /// <param name="ListBoxName">Name of the listbox.</param>
26        private static void RemoveSelectedItem(ListBox ListBoxName)
27        {
28            //Is there a selected item in the listbox?
29            if (ListBoxName.SelectedIndex != -1)
30            {
31                ListBoxName.Items.Remove(ListBoxName.SelectedItem);
32            }
33        }
Usage
private void btnAdd_Click(object sender, EventArgs e)
{
	AddSelectedItem(listBox1, listBox2);
}

private void btnRemove_Click(object sender, EventArgs e)
{
	RemoveSelectedItem(listBox2);
}
Notes
Add two listboxes and buttons to trigger the events.