【发布时间】:2011-12-22 17:44:15
【问题描述】:
我有两个名为 listBox1 和 listBox2 的列表框,两个列表框中都有 4 个项目(字符串)。我可以从两个列表框中选择多个项目。我也有两个按钮。
单击button1 时,我必须将多个选定项目从listBox1 移动到listBox2。同样,在单击button2 时,我必须将多个选定项目从listBox2 移动到listBox1。
怎么做?
【问题讨论】:
我有两个名为 listBox1 和 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);
【讨论】:
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);
【讨论】:
根据这个问题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);
}
}
你可以这样做。
【讨论】:
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);
}
}
【讨论】: