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

// Move selected items from one ListBox to another.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.
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();
}
// Move selected items to lstSelected.The MoveAllItems method shown below moves all of the items from one ListBox to another.
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);
}
// Move all items from one ListBox to another.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.
private void MoveAllItems(ListBox lstFrom, ListBox lstTo)
{
lstTo.Items.AddRange(lstFrom.Items);
lstFrom.Items.Clear();
SetButtonsEditable();
}
// Move all items to lstSelected.The last interesting piece of code is the following SetButtonsEditable method.
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);
}
// Enable and disable buttons.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
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);
}
-->
Comments