How to populate a combobox from two different SQL Server database tables - vb.net

I am trying to create a system that will load items from a database. There are two comboboxes; combobox1 which loads items from database table 1 and combox2 which loads items from database table 2.
Both tables are in the same database.
Here is was I tried but when I run the system I get this error:
(Conversion from string "SELECT * FROM dbo.Dishes" to type 'Long' is not valid.)
Here is the code I'm using:
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
connection.Open()
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
Dim cmd As SqlCommand
cmd = New SqlCommand(query, connection)
Dim reader As SqlDataReader
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("MealName"))
cbxType.Items.Add(reader.Item("DessertName"))
End While
connection.Close()

In VB.NET,AND is an operator.It is used to perform conjunction between either Booleans or Integers/Doubles/any numeric expression.Lets take your query string as an example :
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
You are using AND here to join 2 sentences/strings which wouldn't result in anything rather it is trying to cast it as a Long.
Try to execute this command in SQL and you won't find any luck :(.
Your statements are correct :
SELECT * FROM dbo.Dishes
SELECT * FROM dbo.Desserts
But the way you are trying to achieve your goals is incorrect :(.
To get the data from the database into your combobox, what you can do is either use two comboboxes with separated SQL Queries/SQL Commands or you can use one combobox where you add data from both the databases but separate them with some special characters such as a comma ,
A sample may look like :
With one combobox
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0)) ' Here 0 is the column count,change it as required
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo2.Items.Add(dr2(0)) ' Here 0 is the column count,change it as required
End while
With 1 combobox
Here it gets a bit complicated.Firstly you need to populate your combobox from the data received from the first dataReader.Then, when the 2nd datareader is reading the data , you need to update the existing data/Item of the combobox keeping the existing data/item but adding new data/item to each existing data/item(separating them with ,).
Sample :
Dim i as Integer
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0))
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo1.Items(i) = myconbo1.Items(i) & "," & dr2(0)
i = i + 1
End while
Now, NOTE THAT I AM USING MULTIPLE DATAREADERS WITH THE SAME CONNECTION ,SO YOU MAY NEED TO INCLUDE MultipleActiveResultSets=True IN YOUR CONNECTION STRING or ENCLOSE THE DATAREADERS IN USING STATEMENTS or CALL dataReader.Close AFTER EACH DATAREADER HAS COMPLETED READING FROM THE DATABASE
This will solve your issue :)

Looks like you don't know how to write SQL queries (and your VB syntax itself looks faulty - string AND string?).
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
Dim query As String = <cmdString>
SELECT MealName as Name FROM dbo.Dishes
union
SELECT DessertName as Name FROM dbo.Desserts
</cmdString>
Dim cmd As SqlCommand
Dim reader As SqlDataReader
connection.Open()
cmd = New SqlCommand(query, connection)
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("Name"))
End While
connection.Close()
Note: You are saying 2 comboboxes but your code seemed to be loading all the items to a single combobox. If you really need 2 comboboxes then use 2 SqlCommand and Reader loops (actually it would be better if you simply have used Linq for this).

You should be a bit more specific on what columns you are pulling from the 2 tables. if they are similar, you could write a sql query to UNION ALL the fields with a simple control to identify which record came from which table.
Example of SQL command string:
"SELECT 'M' AS Ctl, MealName AS aName FROM dbo.Dishes " &
"UNION ALL " &
"SELECT 'D' AS Ctl, DessertName AS aName FROM dbo.Desserts"
As mentioned by many here already, it seems like you are referencing only 1 ControlBox to list the fields returned cbxType
below is the reader (adapted to 2 ComboBoxes):
While reader.Read
Select Case reader.Item("Ctl")
Case "M"
cbxMType.Items.Add(reader.Item("aName"))
Case "D"
cbxDType.Items.Add(reader.Item("aName"))
End Select
End While
Hope this helps

Related

Syntax error (missing operator) in query expression in OleDb vb.net

Please give me a solution.
I think I made the query code wrong
Private Sub PopulateDataGridView()
Dim query = "select ITM,ITC,QOH,PRS FROM IFG (WHERE QOH > 0 AND ITM = #ITM OR ISNULL(#ITM, '') = '')"
Dim constr As String = "provider=Microsoft.Jet.OLEDB.4.0; data source=C:\Users\ADMIN2\Desktop; Extended Properties=dBase IV"
Using con As OleDbConnection = New OleDbConnection(constr)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#ITM", cbCountries.SelectedValue)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
Syntax error in FROM clause.
contents of the database
It's a question about SQL syntax, really, and not so much vb.net or oledb.
You had two WHERE clauses, which is invalid SQL. Change the second WHERE to AND
Dim query As String = "select ITM,ITC,QOH,PRS FROM IFG WHERE QOH > 0"
query &= " AND ITM = #ITM"
By the way, since strings are immutable in vb.net, you should not build a string like that (first assigning to, then adding to) when you so clearly can avoid it because every concatenation creates a new string in memory. You can either use &, a StringBuilder, or one long string. For example, taking advantage of vb.net syntax to make a multiline string, you can change the vb.net to
Dim query = "
select ITM,ITC,QOH,PRS
FROM IFG
WHERE QOH > 0
AND ITM = #ITM"
which is [subjectively] much easier to read as a SQL query (add the proper parentheses based on your logic, of course!).
Based on your update, you need to add a parameter to the query. Here is a more or less complete example of a query with one parameter
Using con As New OleDbConnection("connection string")
Dim query = "
select ITM,ITC,QOH,PRS
FROM IFG
WHERE QOH > 0
AND ITM = #ITM"
Using cmd As New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#ITM", itmValue)
Using rdr = cmd.ExecuteReader()
For Each result In rdr.AsQueryable()
' do something with each result
Next
End Using
End Using
End Using

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

How can I read a specific column in a database?

I hava a Table named DTR_Table it has 8 columns in it namely:
EmployeeID,Date,MorningTime-In,MorningTime-Out,AfternoonTime-In,AfternoonTime-Out,UnderTime,Time-Rendered.I want to read the column "AfternoonTime-In".
Following is my code. It reads my "AfternoonTime-In" field, but it keeps on displaying "Has Rows" even if there is nothing in that column.
How can I fix this?
Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR Where Date = #Date and EmployeeID = #EmpID "
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.AddWithValue("#Date", DTRform.datetoday.Text)
cmd1.Parameters.AddWithValue("#EmpID", DTRform.DTRempID.Text)
Using Reader As SqlDataReader = cmd1.ExecuteReader()
If Reader.HasRows Then
MsgBox("Has rows")
Reader.Close()
Else
MsgBox("empty")
End If
End Using`
After returning the DataReader you need to start reading from it if you want to extract values from your query.
Dim dt = Convert.ToDateTime(DTRform.datetoday.Text)
Dim id = Convert.ToInt32(DTRform.DTRempID.Text)
Using Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR
Where Date = #Date and EmployeeID = #EmpID"
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = dt
cmd1.Parameters.Add("#EmpID", SqlDbType.Int).Value = id
Using Reader As SqlDataReader = cmd1.ExecuteReader()
While Reader.Read()
MessageBox.Show(Reader("AfternoonTime-Out").ToString())
Loop
End Using
End Using
Note that I have changed the AddWithValue with a more precise Add specifying the parameter type. Otherwise, your code will be in the hand of whatever conversion rules the database engine decides to use to transform the string passed to AddWithValue to a DateTime.
It is quite common for this conversion to produce invalid values especially with dates

Several rows in SQL Developer but VB says no rows

Dim Test123 As String
Dim Conn As OleDb.OleDbConnection = New OleDbConnection("Private")
Conn.Open()
Dim mySelectQuery As String = "SELECT mti_part_no,sum(mpcs.shop_inv_history.quantity) As FebQTY from mpcs.shop_inventory, mpcs.shop_inv_history where mpcs.shop_inv_history.date_time Like '%Feb% %2015%' AND comments = 'CHECK ITEM OUT' AND mpcs.shop_inventory.si_key=mpcs.shop_inv_history.si_key AND SHOP_INVENTORY.CATEGORY BETWEEN 900 and 999 AND SHOP_INVENTORY.SCRAP_FLAG <> 1 group by mti_part_no order by FebQTY DESC"
Dim CMD As OleDbCommand = New OleDbCommand(mySelectQuery, Conn)
Dim Myreader As OleDbDataReader
Myreader = CMD.ExecuteReader()
Myreader.Read()
Test123 = Myreader("FebQTY")
There are 180 rows when I copy/paste my query into SQL Developer, however whenever I try to use this in VB.NET to populate my listview, I was getting nothing. So I tossed it into the above code just to see what I was quickly getting back from FebQTY and the error is that there are no rows, same with mti_part_no. Can't figure out what the problem is.

VB - Using data held within a textbox to update a table

How do you use SQL to put data into an empty table? So far in my code I have taken the data from an SQL table and then have put it into a Text Box using the following code:
Dim query As String = "SELECT Pronunciation, Character FROM [Katakana List] WHERE Pronunciation='" & pronunciation & "';"
Dim instruction = New SqlCommand(query, sqlCon)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(Katakana)
Textbox1.text=DT.row(0)("column")
Now that the data is held in the text box, how would I do the reverse of this process to put the data into an empty table. It would help if someone could give me an example of the query I could use to put the data back in.
If you want update data which you get from query before, then use UPDATE-query
If you want insert brand new data then use INSERT - query
'For updating existing data
Dim query As String = "UPDATE [Katakana List] SET Character = #NewCharacter WHERE Pronunciation=#Pronunciation"
'For Inserting new data
Dim query As String = "INSERT INTO [Katakana List] (Character) VALUES (#NewCharacter);"
Using instruction As New SqlCommand(query, sqlCon)
'Better practice to use parameters in query
instruction.Parameters.AddWithValue("#Pronunciation", pronunciation)
instruction.Parameters.AddWithValue("#NewCharacter", Textbox1.text)
instruction.ExecuteNonQuery()
End Using
If you want to set the data in the textbox into datatable just do it like this :
DT.row(0)("column") = Textbox1.text
if you want to enter it into database create query to do so , something like this :
Dim query As String = "Insert Into TableName(col1) Values('"& Textbox1.text &"');"
Dim command = New SqlCommand(query, sqlCon)
command.ExecuteNonQuery()