日期:2014-05-18  浏览次数:20433 次

非常郁闷+奇怪的问题,求教
我用下面的语句要将listbox1中的选定项移动到listbox2
for(int   i=0;i <this.ListBox1.Items.Count;i++)
{
        if(this.ListBox1.Items[i].Selected==true)
        {
        this.ListBox2.Items.Add(new   ListItem(ListBox1.Items[i].Text,this.ListBox1.Items[i].Value));
this.ListBox1.Items.Remove(ListBox1.Items[i]);
        i=i-1;
        }
}
有的页面可以实现,有的页面却出现这样一个怪现象:不管选什么,是不是多选,总是将   listbox1的items[0]这一项移动到listbox2
百思不得其解
绑定数据的语句是放在if(!this.ispostback)里的
还有就是在页面的一个dropdownlist的选中项变化的时候重新绑定数据
代码从这个页面复制到那个页面后也重新注册了事件
到底是哪里疏忽了?大家帮找一下原因


------解决方案--------------------
for (int i = this.ListBox1.Items.Count-1; i> =0 ; i++)
{
if (this.ListBox1.Items[i].Selected == true)
{
this.ListBox2.Items.Add(new ListItem(ListBox1.Items[i].Text, this.ListBox1.Items[i].Value));
this.ListBox1.Items.Remove(ListBox1.Items[i]);
i = i - 1;
}
}
------解决方案--------------------
前面一个问题既然有些页面能实现,有些页面不能实现,那么说明代码问题不大,这就看你比较代码的异同了,其次建议你单步调试一步一步看执行步骤。
第二个问题,不明白你问的什么问题
------解决方案--------------------
第一个问题,在操作listbox这类的控件,如果有add或者remove时,是不能使用for循环的。
假如在remove之前,listbox的item的length = 5,当add过后,就会变成4,当下一次for循环时就会少循环一次,所以,要使用while循环这类的控件
------解决方案--------------------
RemoveAt试试
------解决方案--------------------
做Remove这件事,循环的索引要从大到小写不容易出错
------解决方案--------------------
试试这样吧,没有测试过,基本的思路就是从最后一个item向前循环,这样当你删除最后一个item的时候,index不会被打乱--
for ( int i = ListBox1.Items.Count - 1; i > = 0; i-- )
{
if ( ListBox1.Items[i].Selected )
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.RemoveAt(i);
}
}
------解决方案--------------------
顶!
------解决方案--------------------
要用--的循环
不然再移掉一个之后count数就变了
这样的话下一次进入循环后selectindex就找错地方了。
------解决方案--------------------
给你一段我的代码


#region 左移一个
protected void btnLeft_ServerClick(object sender, EventArgs e)
{
if (this.lstEmp.SelectedIndex == -1)
{
return;
}
int index = this.lstEmp.SelectedIndex;
this.lstManager.Items.Add(
new ListItem(
this.lstEmp.SelectedItem.Text,
this.lstEmp.SelectedItem.Value)
);
this.lstEmp.Items.RemoveAt(index);
if (index != 0 && index < this.lstEmp.Items.Count)
{
this.lstEmp.SelectedIndex = index;
}
else if (index != 0 && index == this.lstEmp.Items.Count)
{
this.lstEmp.SelectedIndex = index - 1;
}
else if (index == 0 && this.lstEmp.Items.Count > 0)
{
this.lstEmp.SelectedIndex = 0;
}
this.lstManager.SelectedIndex = this.lstManager.Items.Count - 1;
}
#endregion

#region 右移一个
protected void btnRight_ServerClick(object sender, EventArgs e)