且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解决“指数超出范围。必须是非负数且小于集合的大小。在ASP .NET中使用C#

更新时间:2022-10-15 21:36:07

提示位于错误消息的小于集合大小部分,因为您正在迭代并包括该大小:

  for (i =  0 ; i <  = ListBox3.Items.Count; i ++)

必须是

  (i =  0 ; i <  ListBox3.Items.Count; i ++)







如理查德所述,您的循环可能会跳过项目,您应该从最后一项开始迭代。

[/编辑]


my code is as follows
i want that i select some items from the list box and the selected items are automatically add on to another list box and remove from the first list box .
in asp.net using c#.

What I have tried:

protected void ListBox3_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void ListBox4_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void Button6_Click(object sender, EventArgs e)
{
int i;
for (i = 0; i <= ListBox3.Items.Count; i++)
{
if (ListBox3.Items[i].Selected == true)
{
ListBox4.Items.Add(ListBox3.SelectedItem);
ListBox3.Items.Remove(ListBox3.SelectedItem);
}
}









}
}

The hint is in the "less than size of the collection" part of the error message because you are iterating up to and including that size:
for (i = 0; i <= ListBox3.Items.Count; i++)

It must be

for (i = 0; i < ListBox3.Items.Count; i++) 



[EDIT]
As noted by Richard, your loop might skip items and you should iterating down starting at the last item.
[/EDIT]