Reputation: 31
I have two listboxes named listBox1
and listBox2
with 4 items (strings) in both listboxes. I can select multiple items from both listboxes. I have also two buttons.
On clicking button1
, I have to move multiple selected items from listBox1
to listBox2
. Similarly, on clicking button2
, I have to move multiple selected items from listBox2
to listBox1
.
How can it be done?
Upvotes: 3
Views: 22683
Reputation: 1
private void Btn_Right_Click(object sender, EventArgs e)
{
while(ListBox_Left.SelectedItems.Count!=0)
{
ListBox_Right.Items.Add(ListBox_Left.SelectedItem);
ListBox_Left.Items.Remove(ListBox_Left.SelectedItem);
}
}
private void Btn_Left_Click(object sender, EventArgs e)
{
while (ListBox_Right.SelectedItems.Count != 0)
{
ListBox_Left.Items.Add(ListBox_Right.SelectedItem);
ListBox_Right.Items.Remove(ListBox_Right.SelectedItem);
}
}
Upvotes: 0
Reputation: 1
private void move(ListBox source, ListBox destination) {
for (int i = 0; i <= source.Items.Count-1; i++)
{
destination.Items.Add(source.Items[i]);
}
source.Items.Clear();
}
Upvotes: 0
Reputation: 21
private void button1_Click(object sender, EventArgs e)
{
foreach (var item in listBox1.SelectedItems)
{
listBox2.Items.Add(item);
}
for (int s = 0; s < listBox1.Items.Count; s++)
{
for (int t = 0; t < listBox2.Items.Count; t++)
{
if (listBox1.Items[s].ToString().Equals(listBox2.Items[t].ToString()))
{
listBox1.Items.RemoveAt(s);
}
}
}
}
Upvotes: 1
Reputation: 1550
According to this question How to remove multiple selected items in ListBox?
private void button1_Click(object sender, EventArgs e)
{
for(int x = listBox1.SelectedIndices.Count - 1; x>= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
listBox2.Items.Add(listBox1.Items[idx]);
listBox1.Items.RemoveAt(idx);
}
}
You can do like this.
Upvotes: 2
Reputation: 31610
private void MoveListBoxItems(ListBox source, ListBox destination)
{
ListBox.SelectedObjectCollection sourceItems = source.SelectedItems;
foreach (var item in sourceItems)
{
destination.Items.Add(item);
}
while (source.SelectedItems.Count > 0)
{
source.Items.Remove(source.SelectedItems[0]);
}
}
Use: On the click event of your move from 1 to 2 button:
MoveListBoxItems(listBox1, listBox2);
To move them back:
MoveListBoxItems(listBox2, listBox1);
Upvotes: 5
Reputation: 7591
private void Move(ListControl source, ListControl destination)
{
List<ListItem> remove = new List<ListItem>();
foreach(var item in source.Items)
{
if(item.Selected == false) continue;
destination.Items.Add(item);
remove.Add(item);
}
foreach(var item in remove)
{
source.Items.Remove(item);
}
}
then you can call it like this
Move(listbox1, listbox2);
//or
Move(listbox2, listbox1);
Upvotes: 2