vb.net 中出现超出范围错误并访问 get maxnumber

out of range error in vb.net and access get maxnumber

我正在尝试从 table 中获取最大数字并将其插入另一个数字 使用 vb.net 2008 并访问 db 2003 这是我的代码 </p> <pre><code>Dim strQ As String = "SELECT MAX(IDbatch) from batches " Dim IDbatch As Integer Dim cmdQ As OleDbCommand = New OleDbCommand(strQ, con) If Not con.State = ConnectionState.Open Then con.Open() End If Dim QReader As OleDbDataReader Dim it As Integer QReader = cmdQ.ExecuteReader If QReader.FieldCount > 0 Then While QReader.Read it = QReader.Item("IDbatch") MsgBox(it) End While End If

我遇到了超出范围的错误

将您的查询更改为

Dim strQ As String = "SELECT MAX(IDbatch) as MaxIDbatch from batches "

以及将值读取到

的代码
it = QReader.Item("MaxIDbatch")

正如您现在所拥有的那样,MAX(IDbatch) 创建了一个名称与 IDbatch 不同的字段,并且尝试使用名称 IDbatch 检索该字段的内容失败了 Index out of range exception

顺便说一句,在批次 table 中没有记录的情况下,您对 FieldCount > 0 的检查也将始终为真。所以,如果你这样做是为了在没有记录的情况下进行保护,那么最好写

Dim result = cmdQ.ExecuteScalar()
if result IsNot Nothing then
    Dim it = Convert.ToInt32(result)
    MsgBox(it)
End If

通过这种方法,您还可以省略 IDbatch 字段上的别名