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))
在上面的代码中,数组中的值如下
roll = 21,22,23,24,25,26,27,28,29,30(所有学生的rollNos) 在课堂上)
txtlist.text value = 21,22(意味着这两个人没有上课)
现在我需要保存缺席阵列中的缺席卷并且阵列中剩余的卷存在
缺席列表被正确保存但第二个MsgBox显示0而不是23
代码有什么问题
答案 0 :(得分:4)
VB.NET中的数组是从零开始的。您正在从索引1开始设置滚动值:
Dim i As Short = 1
然后当你正在读取datareader时,你将从索引1开始加载到roll数组中。
'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查询。
答案 1 :(得分:0)
Dim i As Short = 1
应该是
Dim i As Short = 0
这解决了问题