Question

I want to retrieve the price from table Products to use it as label2 on the orderinfo form.

    Dim con As New OleDb.OleDbConnection
    Dim com As New OleDb.OleDbCommand
    com = New OleDb.OleDbCommand("Select Price FROM Products WHERE ProductName='" & ListBox1.SelectedItem.ToString & "'", con)
    con.ConnectionString = "PROVIDER = Microsoft.ACE.OLEDB.12.0; Data Source=Database_AntoninosCafe.accdb"
    con.Open()
    com.ExecuteNonQuery()
    orderInfo.Label2.Text = retrieve data
    con.Close()

No correct solution

OTHER TIPS

The correct approach to your simple problem

Dim cmdText = "Select Price FROM Products WHERE ProductName=?"
Using con = New OleDb.OleDbConnection( ... connection string here ...)
Using com = New OleDb.OleDbCommand(cmdText, con)
   com.Parameters.AddWithValue("@p1", ListBox1.SelectedItem.ToString)
   con.Open()
   Using reader = com.ExecuteReader()
       if reader.Read() Then
          orderInfo.Label2.Text = reader("Price").ToString
       End If
   End Using  
End Using
End Using

The first thing is to use a parameterized query to avoid sql injections and parsin problems, then use the Using statement to encapsulate you disposable object in a block of code that ensures the closing and disposing of these objects. Finally, to read data from a datatable you use the ExecuteReader command that returns an OleDbDataReader instance. It is this instance that could be used to extract the data from your database

As a side note, I have used, as placeholder for the parameter, a question mark. This is the predefined symbol used by OleDb. But, when adding the parameter value to the collection, I have used a different name (@p1). This is acceptable because OleDb do not use the parameter names to find the corresponding placeholders in the query text like the SqlClient or other providers, but use the position of the placeholder. So, first placeholder replaced by the first parameter and so on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top