在学习asp.net的ListBox控件时
当ListBox1插入到ListBox2中时
首先,应取出Listbox1中的item值,使用foreach遍历添加到ListBox2中
for (int i = 0; i < this.ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
ListBox2.Items.Add(listby.Items[i]);
this. ListBox1.Items.Remove(listby.Items[i]);
}
}
此时并不能取出所有你选中的值,比如我们选中两项,这时根据索引进入for循环,当第一个元素被删除后,第二个元素的value属性值减一,所以找不到原来符合if条件的value所对应的项。所以应该使用倒遍历的方式
List<ListItem> list = new List<ListItem>();
for (int i = this. ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected == true)
{
list.Add(ListBox1.Items[i]);
this. ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
再遍历item