VB.NET For循环不能正常运行

时间:2014-04-25 12:50:08

标签: vb.net for-loop

我一直在调试我的for循环,我发现它没有通过它到达某一行的代码进行运行该行一旦运行就会回到该行并再次运行它因此导致以下错误。< / p>

  

指数超出范围。必须是非负数且小于集合的大小。
      参数名称:index

这是我的for循环:

For Each user As Data.DataRow In userData.Rows
    If user Is Nothing Then
        Exit For
    End If
    memberList(userId) = New clsMember(user("UserID"), user("Firstname"), user("Secondname"), user("Username"), user("Password"), user("Email"), user("Rights"))
    userId += 1
Next

它被困的线是:

memberList(userId) = New clsMember(user("UserID"), user("Firstname"), user("Secondname"), user("Username"), user("Password"), user("Email"), user("Rights"))

虽然调试我发现它运行第一次完全回到for循环尝试再次运行它而不进入下一行:

userId += 1

导致错误,我根本不知道为什么这样做。
如果您需要更多代码,我将很乐意提供它。

1 个答案:

答案 0 :(得分:2)

将项目添加到列表中时(假设尚未填充),您只需选择您想要占用项目的索引并为其指定值。该列表需要首先有一个占位符。

最简单的方法就是使用List.Add()将项目添加到列表中:

For Each user As Data.DataRow In userData.Rows
    memberList.Add(New clsMember(user("UserID"), 
                                 user("Firstname"),
                                 user("Secondname"), 
                                 user("Username"), 
                                 user("Password"), 
                                 user("Email"), 
                                 user("Rights"))
Next