Moving Items between two Listboxes in C#

This example shows how you can move items between two listboxes by double-clicking on the items.

To start you need a form, with two listboxes (I labelled mine lstLeft and lstRight). I also added a button (btnList with the caption “Load List”) to populate lstLeft with some items to play with (and reset the form). So, in design view my form looks like the one below.

Firstly the code to add items to lstLeft which is added to the Click event of the button:

        private void btnList_Click(object sender, EventArgs e)
        {
            lstRight.Items.Clear();
            lstLeft.Items.Clear();

            lstLeft.Items.Add('Cheese');
            lstLeft.Items.Add('Ham');
            lstLeft.Items.Add('Egg');
            lstLeft.Items.Add('Bacon');
            lstLeft.Items.Add('Avacado');
            lstLeft.Items.Add('Melon');
            lstLeft.Items.Add('Sausage');
            lstLeft.Items.Add('Monkey Brain');
            lstLeft.Items.Add('Peas');
            lstLeft.Items.Add('Carrots');
        }

So we have cleared both lists, and added several items to lstLeft.

Next we need to add the code to move the items from one list to the other when an item is doubled clicked. So, we add the following code to the DoubleClick event of each listbox:

        private void lstLeft_DoubleClick(object sender, EventArgs e)
        {
            if (lstLeft.SelectedIndex != -1)
            {
                lstRight.Items.Add(lstLeft.SelectedItem);
                lstLeft.Items.Remove(lstLeft.SelectedItem);
            }
        }

        private void lstRight_DoubleClick(object sender, EventArgs e)
        {
            if (lstRight.SelectedIndex != -1)
            {
                lstLeft.Items.Add(lstRight.SelectedItem);
                lstRight.Items.Remove(lstRight.SelectedItem);
            }
        }

Firstly we check to make sure an item has been selected in the list, by checking the SelectedIndex > -1. We then add the selected item to the other list and remove the selected item from the double-clicked list.

Runtime form view:

Now you should find that when you click the button lstLeft is populated and lstRight is cleared, and if you double-click an item in lstLeft it moves to lstRight and vice versa!

Advertisements
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s