Use buttons to let the user move items between two ListBoxes in C#

One way tp let the user select items from a list is to use a ListBox. Another method is to let the user move items between a "selected" ListBox and a "not selected" ListBox.

The program uses the MoveSelectedItems method shown below to move items from one ListBox to the other.

// Move selected items from one ListBox to another.
private void MoveSelectedItems(ListBox lstFrom, ListBox lstTo)
{
while (lstFrom.SelectedItems.Count > 0)
{
string item = (string)lstFrom.SelectedItems[0];
lstTo.Items.Add(item);
lstFrom.Items.Remove(item);
}
SetButtonsEditable();
}

While the source ListBox has selected items, the code adds the first selected item to the destination ListBox and then removes it from the source ListBox.

The following code shows how the program uses this method to move items when the user clicks the < and > buttons.

// Move selected items to lstSelected.
private void btnSelect_Click(object sender, EventArgs e)
{
MoveSelectedItems(lstUnselected, lstSelected);
}

// Move selected items to lstUnselected.
private void btnDeselect_Click(object sender, EventArgs e)
{
MoveSelectedItems(lstSelected, lstUnselected);
}

The MoveAllItems method shown below moves all of the items from one ListBox to another.

// Move all items from one ListBox to another.
private void MoveAllItems(ListBox lstFrom, ListBox lstTo)
{
lstTo.Items.AddRange(lstFrom.Items);
lstFrom.Items.Clear();
SetButtonsEditable();
}

This code uses the ListBox's AddRange method to quickly add all of the source ListBox's items to the destination ListBox. It then clears the source ListBox.

The following code shows how the program moves items when the user clicks the << and >> buttons.

// Move all items to lstSelected.
private void btnSelectAll_Click(object sender, EventArgs e)
{
MoveAllItems(lstUnselected, lstSelected);
}

// Move all items to lstUnselected.
private void btnDeselectAll_Click(object sender, EventArgs e)
{
MoveAllItems(lstSelected, lstUnselected);
}

The last interesting piece of code is the following SetButtonsEditable method.

// Enable and disable buttons.
private void SetButtonsEditable()
{
btnSelect.Enabled = (lstUnselected.SelectedItems.Count > 0);
btnSelectAll.Enabled = (lstUnselected.Items.Count > 0);
btnDeselect.Enabled = (lstSelected.SelectedItems.Count > 0);
btnDeselectAll.Enabled = (lstSelected.Items.Count > 0);
}

This method makes the <, <<, >, and >> enabled or disables depending on whether items are selected in the ListBoxes. Both ListBoxes' SelectedIndexChanged event handlers plus any code that changes the items in a ListBox call this method to make sure only the useful buttons are enabled at any time.

Download example


-->