我正在使用C#编写Windows窗体。我有两个名为listBox1
和listBox2
的列表框。我在两个列表框中都有4个项目。我可以从两个列表框中选择多个项目。我还有两个按钮。点击button1
后,我必须将多个选定项目从listBox1
移至listBox2
。同样,点击button2
后,我必须将多个选定项目从listBox2
移至listBox1
。如何在C#中完成?
提前致谢。
答案 0 :(得分:4)
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);
答案 1 :(得分:2)
ListBox
具有SelectedItems
属性,您可以使用该属性复制按钮的单击事件处理程序中的项目。像这样:
foreach(var item in listBox1.SelectedItems)
{
listBox2.Items.Add(item);
}
答案 2 :(得分:2)
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);
答案 3 :(得分:2)
根据这个问题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);
}
}
你可以这样做。
答案 4 :(得分:1)
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);
}
}
}
}
答案 5 :(得分:0)
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();
}
答案 6 :(得分:0)
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);
}
}