[英]How to move multiple selected item from one listbox to another listbox?
我有两个名为listBox1
和listBox2
列表框,两个列表listBox2
都有 4 个项目(字符串)。 我可以从两个列表框中选择多个项目。 我也有两个按钮。
单击button1
,我必须将多个选定项目从listBox1
移动到listBox2
。 同样,在单击button2
,我必须将多个选定项目从listBox2
移动到listBox1
。
如何做呢?
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]);
}
}
使用:在您从 1 移到 2 按钮的点击事件上:
MoveListBoxItems(listBox1, listBox2);
将它们移回:
MoveListBoxItems(listBox2, listBox1);
根据这个问题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);
}
}
你可以这样做。
ListBox
有一个SelectedItems
属性,您可以使用它来复制按钮的单击事件处理程序中的项目。 像这样:
foreach(var item in listBox1.SelectedItems)
{
listBox2.Items.Add(item);
}
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);
}
}
那么你可以这样称呼它
Move(listbox1, listbox2);
//or
Move(listbox2, listbox1);
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);
}
}
}
}
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();
}
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.