0
    Dim count as Short = 10
    Dim roll(count), absent(count), present(count) As Short
    Dim i As Short = 1
    query = "SELECT * FROM primary_student_table WHERE admityear=" & year & " AND batch= " & batch & ""
    con.Open()
    cmd = New SqlCommand(query, con)
    re = cmd.ExecuteReader
    While re.Read
            roll(i) = re("roll")
            i += 1
    End While
    con.Close()

    absent = txtlist.Text.Split(","c).Select(Function(s) Short.Parse(s)).ToArray()
    present = roll.Except(absent).ToArray()
        MsgBox(absent(0))
        MsgBox(present(0))

In the above code, the values in the arrays are as follows

  • roll=21,22,23,24,25,26,27,28,29,30 (rollNos of all the students in the class)

  • txtlist.text value = 21,22 (meaning those two were absent for the class)

Now I need to save the absentees rolls in the array absent and the rest of the rolls in array present

The absentees list gets saved correctly but the second MsgBox is displaying 0 instead of 23

What's wrong with the code

4

2 回答 2

4

VB.NET 中的数组是从零开始的。您正在从索引 1 开始设置滚动值:

Dim i As Short = 1

然后,当您读取数据读取器时,您将从索引 1 开始加载到滚动数组中。

'i is set to 1, so you're setting values from the second array item onwards
While re.Read
        roll(i) = re("roll")
        i += 1
End While

所以 roll(0) 的值始终为 0,这将被发送到您当前的数组。

从 datareader 读取时,您可能没有得到索引越界异常的原因是因为您的 datareader 返回 10 行,并且您的 roll 数组可以容纳 11(roll(10) 实际上是 11 的数组)。

将i的值设置为0,应该没问题:

Dim i As Short = 0

编辑: 根据 Tim Schmelter 的建议,您确实应该考虑使用 List(Of T) 而不是数组。另外,考虑使用参数化的 sql 查询。

于 2013-07-22T15:09:06.017 回答
0
Dim i As Short = 1

本来应该

Dim i As Short = 0

这解决了问题

于 2013-07-22T15:10:23.193 回答