从数据库在vb.net中的数据网格中插入数据

时间:2013-02-21 17:00:44

标签: vb.net

我正在尝试从数据库中检索数据。我可以连接到数据库并检索数据,但是当我尝试将其放入数据网格时,我收到错误消息

  

索引超出范围异常未处理ORDERDETAILS.PRODUCTID。

SQL语句有效,但不确定将其输入数据网格的代码。任何帮助将不胜感激。

    Dim conn As New OleDb.OleDbConnection
    conn.ConnectionString = _
    "Provider=msdaora;Data Source=orabis;User Id=112221739;Password=112221739;"

    conn.Open()


    Dim work As Integer
    work = CInt(ComboBox1.SelectedItem)

    Dim cmd As New OleDbCommand


    cmd = conn.CreateCommand()


    cmd.CommandText = "SELECT     ORDERDETAILS.PRODUCTID,PRODUCTS.PRODUCTDESCRIPTION,ORDERDETAILS.ORDERQUANTITY,ORDERDETAILS. ORDERQUANTITYTOTAL FROM CUSTOMER, ORDERS, ORDERDETAILS, PRODUCTS  WHERE CUSTOMER.CUSTOMERID = ? AND CUSTOMER.CUSTOMERID = ORDERS.CUSTOMERID AND ORDERS.ORDERID = ORDERDETAILS.ORDERID AND ORDERDETAILS.PRODUCTID = PRODUCTS.PRODUCTID"
    cmd.CommandType = CommandType.Text

    cmd.Parameters.AddWithValue("?", work)
    Dim dr As OleDb.OleDbDataReader
    dr = cmd.ExecuteReader()
    If dr.HasRows Then
          DataGridView1.Rows.Add(CInt(dr.Item("ORDERDETAILS.PRODUCTID")),        CStr(dr.Item("PRODUCTS.PRODUCTDESCRIPTION")), CInt(dr.Item("ORDERDETAILS.ORDERQUANTITY")), CInt(dr.Item("ORDERDETAILS.ORDERQUANTITYTOTAL")))
    End If
    dr.Close()
    cmd.ExecuteNonQuery()

1 个答案:

答案 0 :(得分:0)

在获取值之前,您需要从datareader读取数据。

If dr.Read Then
      DataGridView1.Rows.Add(CInt(dr.Item("ORDERDETAILS.PRODUCTID")),        CStr(dr.Item("PRODUCTS.PRODUCTDESCRIPTION")), CInt(dr.Item("ORDERDETAILS.ORDERQUANTITY")), CInt(dr.Item("ORDERDETAILS.ORDERQUANTITYTOTAL")))
End If