开发者

C# multiple selection listbox move

What I have is two listboxs.

In listbox1 I want the user to be able to click a button and move all selected items to listbox two. Also if there is nothin开发者_运维技巧g selected i dont want the button to work. Anybody have any suggestions?

listbox1.items.add(listbox2.selecteditems); just moves over (collection) to the 2nd listbox.


I guess you will need to move the items separately:

List<object> itemsToRemove = new List<object>();

foreach (var item in listbox2.SelectedItems)
{
    listbox1.Items.Add(item);
    itemsToRemove.Add(item);
}

foreach (var item in itemsToRemove)
{
    listbox2.Items.Remove(item);
}

This will move any selected items from listbox2 to listbox1. The itemsToRemove list is used as a temporary storage since you cannot modify a collection while iterating over it; while iterating we just add references to the items to be removed into a temporary list, then we iterate over that list and remove the items.

In order to handle the case when no items are selected, I would set up an event handler for the SelectedIndexChanged event, and set the Enabled property of the button:

theButton.Enabled = (listbox2.SelectedItems.Count > 0);


Here's a solution using Linq:

private void buttonMove_Click(object sender, EventArgs e)
{
    foreach (var item in listBox1.SelectedItems.OfType<object>().ToArray())
    {
        listBox1.Items.Remove(item);
        listBox2.Items.Add(item);
    }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    buttonMove.Enabled = listBox1.SelectedItems.Count > 0;
}


for Winforms:

foreach (var i in listbox1.SelectedItems) {
     listbox2.SelectedItems.add(i);
}

To enable the button only when necessary add code to the OnSelectionChanged event and set button1.enabled = (Listbox1.SelectedItems.Count > 0);


if (listbox1.SelectedItems.Count == 0)
{
    return;
}

// Do this if you want to clear the second ListBox
listbox2.Items.Clear();

foreach (object obj in listbox1.SelectedItems)
{
    listbox2.Items.Add(obj);
}


For Listbox1 use the SelectedItemChanged Event and use your EventArgs provided to get the selected item -> then add to listbox2.

If no item is selected button.enbabled = false;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜