【问题标题】:How to fix 'System.IndexOutOfRangeException: 'There is no row at position 0.' error?如何修复'System.IndexOutOfRangeException:'位置 0 处没有行。'错误?
【发布时间】:2019-06-03 15:56:31
【问题描述】:

我正在使用 SQL 和 OLEDB 在 VB.NET 中创建一个登录系统(如果有帮助的话)。我正在尝试在表格中插入一个新项目,但我不断收到异常,我该如何解决?

我尝试简单地将这一行 Dim comd As New OleDb.OleDbCommand(sql, Connstring) 中的数字零更改为其他数字,并将记录号更改为表中的记录数。

Dim sql As String = "INSERT INTO UserInfo (Username, Password, CurrentLevel) VALUES (?, ?, ?)"
Dim comd As New OleDb.OleDbCommand(sql, Connstring)                    
comd.Parameters.AddWithValue(0, tblTable.Rows(recordno)(0))            
comd.Parameters.AddWithValue("@Username", tblTable.Rows(2)(recordno))
comd.Parameters.AddWithValue("@Password", tblTable.Rows(3)(recordno))
comd.Parameters.AddWithValue("@CurrentLevel", tblTable.Rows(4)(recordno))
comd.ExecuteNonQuery() 'run the code to Insert back to the db file

我希望代码会在表中添加另一个条目UserInfo,但除了异常之外什么都没有发生

System.IndexOutOfRangeException: 位置 0 处没有行。

【问题讨论】:

  • 您的四个参数中的 recordno 索引位置似乎不一致。顺便说一句,您的查询只有三个参数。
  • 你有 3 个问号和 4 个参数。
  • 什么是recordno,它来自哪里? .Rows(0)(0) 是第一行第一列。
  • 您可能想阅读Can we stop using AddWithValue
  • 我已经意识到这个问题,我实际上并没有这个表格上的表格,这是错误的来源,感谢您的回复!

标签: sql vb.net ms-access oledb


【解决方案1】:

这表明您的 tblTable 中没有任何行,并且由于您试图获取第一行 (...tblTable.Rows(0)...),因此会引发错误。

【讨论】:

    【解决方案2】:

    这很难阅读/理解:

    comd.Parameters.AddWithValue(0, tblTable.Rows(recordno)(0))  
    

    更好的做法是使用带有参数名称的字符串参数,是的,我知道AddWithValue 有一个带有数字的重载,但这很容易变得无序并且难以识别数字映射到哪个参数,所以明确并使用 paramName:

    comd.Parameters.AddWithValue("paramName", tblTable.Rows(recordno)(0))  
    

    然后我们遇到实际问题:

    tblTable.Rows(recordno)(0)    
    

    你做错了,应该是:

    tblTable.Rows(0)(recordno)      
    

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      相关资源
      最近更新 更多