asp.net控件之ListBox

来源:互联网 发布:网络测速工具 编辑:程序博客网 时间:2024/05/16 07:44

在学习asp.netListBox控件时

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

原创粉丝点击