0

我收到以下代码的错误,指出索引不正确。我假设这是 SQL 语句的错误,但我不确定出了什么问题。

        Private Sub btnStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStock.Click
    frmStock.Visible = True
    Dim SQLCmd As String
    SQLCmd = "SELECT PartID,PartName,PartStockLevel,MakeName,ModelName FROM tblParts WHERE PartStockLevel <= StockWarnLevel;"
    RunSQLCmd("dt", SQLCmd)
    Dim inc As Integer = 0
    Dim NoLowStock As Boolean
    If DataTable IsNot Nothing AndAlso DataTable.Rows.Count > 0 Then
        frmStock.txtPartID.Text = DataTable.Rows(inc).Item(0)
        frmStock.txtName.Text = DataTable.Rows(inc).Item(1)
        frmStock.NUDStockLvl.Value = DataTable.Rows(inc).Item(2)
        frmStock.txtMake.Text = DataTable.Rows(inc).Item(3)
        frmStock.txtModel.Text = DataTable.Rows(inc).Item(4)
    Else
        frmStock.lblLowStock.Visible = True
        frmStock.btnFirstRecord.Visible = False
        frmStock.btnIncDown.Visible = False
        frmStock.btnIncUp.Visible = False
        frmStock.btnLastRecord.Visible = False
        NoLowStock = True
    End If
    If NoLowStock = False Then
        frmStock.Panel1.Visible = False
    End If
End Sub

    Public Sub RunSQLCmd(ByVal DTorDS As String, ByRef SQLCmd As String)
    DataAdapter = New OleDb.OleDbDataAdapter(SQLCmd, con)
    ConnectDB()
    Try
        If DTorDS = "dt" Then
            DataTable = New DataTable
            DataAdapter.Fill(DataTable)
        Else
            DataSet = New DataSet
            DataAdapter.Fill(DataSet, "srcDataSet")
        End If
    Catch ex As Exception
        con.Close()
    End Try
    con.Close()
End Sub

提前致谢!

4

2 回答 2

1

该错误可能来自您查看结果中不存在的行索引。在尝试获取数据之前,您应该检查表是否有行。

像这样: If DataTable IsNot Nothing AndAlso DataTable.Rows.Count >0 Then ... 代码在这里... End If

于 2012-04-07T21:06:33.477 回答
0

试试这个简单的方法

dim dt as new datatable

using connection as new sqlconnection("server=SERVER;database=DATABASE;uid=USERID;pwd=PASSWORD")
connection.open()
     using cmd as new sqlcommand("SELECT PartID,PartName,PartStockLevel,MakeName,ModelName FROM tblParts WHERE PartStockLevel <= StockWarnLevel", connection)
     dt.load(cmd.executereader)
     end using
end using
于 2012-04-12T23:37:28.787 回答