populate a combobox using a selection in another combobox from excel sheet - vb.net

Hi i need to populate a combobox using the selected value in another combo. The coding that i use doesn't produce the required output. i have an excel sheet with columns called "BaseStation" & "SectorID". Combobox2 must display the related sector id with respect to the selected BaseStation
Given below is the error that i get:
"Syntax error (missing operator) in query expression 'BaseStation='."
Please help. the coding given below:
Private Sub ComboBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.TextChanged
Using cn As New OleDb.OleDbConnection With _
{ _
.ConnectionString = _
<S>
provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\WalkAir Customers.xls;
Extended Properties="Excel 8.0; HDR=Yes;"
</S>.Value _
}
Dim cmd As New OleDb.OleDbCommand
Dim dr As System.Data.IDataReader
cn.Open()
cmd = New OleDb.OleDbCommand()
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM [Sheet1$] WHERE BaseStation=" & ComboBox1.Text
Dim dtData As New DataTable
dr = cmd.ExecuteReader
dtData.Load(dr)
dtData.Columns("SectorID").ColumnMapping = MappingType.Hidden
bsCustomers.DataSource = dtData
End Using
ComboBox2.DisplayMember = "SectorID"
ComboBox2.DataSource = bsCustomers
End Sub

Try putting single quotes around the BaseStation parameter:
cmd.CommandText = "SELECT * FROM [Sheet1$] WHERE BaseStation='" & ComboBox1.Text & "'"

Related

How to take data from access data to Combobox

Public Class AdminP_Time2
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
Dim dr As OleDbDataReader
Private Sub AdminP_Time2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;")
conn.Open() 'opens the connection
sql = "SELECT * FROM LecturerName"
cmd = New OleDbCommand(sql, conn)
dr = cmd.ExecuteReader
If dr.Read = True Then
ComboBox1.Text = dr("LecturerName")
End If
why my combobox just show me 1 item ? can anyone help me ? i want take my access data to Combobox.
The reason that your own code doesn't work is that you're only reading one record. You need a loop, e.g.
While dr.Read()
ComboBox1.Items.Add(dr("LecturerName"))
End While
That said, your code should look more like this:
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;"),
cmd As New OleDbCommand("SELECT * FROM LecturerName", conn)
conn.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(dr)
With ComboBox1
.DisplayMember = "LecturerName"
.DataSource = tbl
End With
End Using
End Using
That will load the data into a DataTable and bind that to the ComboBox. You should also set the ValueMember of the ComboBox if you want to be able to access the PK value of the selected record via the SelectedValue of the ComboBox. You should also specify what columns you want to retrieve data from rather than using a wildcard unless you genuinely want every column.
Here is a good example.
Sub TryThis()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdf = db.QueryDefs("qryStaffListQuery”)
strSQL = "SELECT tblStaff.* ” & _
"FROM tblStaff ” & _
"WHERE tblStaff.Office='" & Me.cboOffice.Value & "’ ” & _
"AND tblStaff.Department='" & Me.cboDepartment.Value & "’ ” & _
"AND tblStaff.Gender='" & Me.cboGender.Value & "’ ” & _
"ORDER BY tblStaff.LastName,tblStaff.FirstName;”
End Sub
You can find all details from the link below.
http://www.fontstuff.com/access/acctut17.htm

Data type mismatch in criteria expression.

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
If R2.Checked Then
da = New OleDbDataAdapter("Select * from [maint] where
[centrale]='" & centralev.Text & "' ", MyConn) 'Change items to your
database name
End If
If R1.Checked Then
da = New OleDbDataAdapter("Select * from [maint] where
datevisite='" & dateintervention.Value.ToShortDateString() & "' ",
MyConn) 'Change items to your database name
End If
da.Fill(ds, "maint") 'Change items to your database name
Dim view As New DataView(tables(0))
source1.DataSource = view
DGV.DataSource = view
End Sub
End Class
I used 2 buttonradio to select criteria of search , I have problem with date search, Data type mismatch in criteria expression.
try to change
incorrect
da = New OleDbDataAdapter("Select * from [maint] where
datevisite='" & dateintervention.Value.ToShortDateString() & "' ",
MyConn) 'Change items to your database name
correct
da = New OleDbDataAdapter("Select * from [maint] where
datevisite='" & dateintervention.Value.ToString("yyyy-MM-dd") & "' ",
MyConn) 'Change items to your database name
Example for format
Expanding on Plutonix comment to your question you can try:
Dim cmd = New OleDbCommand("Select * from [maint] where datevisite = ?")
Dim param = New OleDbParameter("#datevisite", OleDbType.Date)
param.Value = dateintervention.Value
cmd.Parameters.Add(param)
da = New OleDbDataAdapter (cmd, MyConn)
In this way ADO.NET will take care for you to replace the question mark in the query text with the proper date value formatted as required by OleDb syntax. You entirely avoid string concatenation errors and you don't need to learn any formatting rule for all available OleDb data types.
Besides it should be safer.

How to create a query in Visual Studio 2013 using Visual Basic

I have the following code and through debugging the problem begins at the While loop. I am trying to retrieve information from 2 tables and insert it into the table created. The information is not being inserted into the table and I am getting blank rows.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=M:\ICT-Group-Project\DeepBlueProject\DeepBlueProject\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT CruiseID, RouteID FROM Cruise WHERE CruiseID =?"
Dim RouteQuery As String = "SELECT RouteName FROM Route WHERE RouteID =?"
Dim cmd As OleDbCommand = New OleDbCommand(CruiseQuery, cn)
Dim cmd2 As OleDbCommand = New OleDbCommand(RouteQuery, cn)
cmd.Parameters.AddWithValue("?", Route_Txt.Text)
Dim reader As OleDbDataReader
reader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "Route"
While reader.Read()
Dim rID As String = reader("RouteID").ToString()
cmd2.Parameters.AddWithValue("?", rID)
Dim reader2 As OleDbDataReader = cmd2.ExecuteReader()
'MsgBox(reader.GetValue(0) & "," & reader.GetValue(1))
row = reader("CruiseID") & "," & reader2("RouteName")
RCTable.Rows.Add(row)
cmd.ExecuteNonQuery()
reader2.Close()
End While
reader.Close()
cn.Close()
End Sub
End Class
If I understand your tables structure well then you could just run a single query extracting data from the two table and joining them in a new table returned by the query
Dim sql = "SELECT c.CruiseID c.CruiseID & ',' & r.RouteName as Route " & _
"FROM Cruise c INNER JOIN Route r ON c.RouteID = c.RouteID " & _
" WHERE c.CruiseID = #cruiseID"
Dim cmd As OleDbCommand = New OleDbCommand(sql, cn)
cmd.Parameters.Add("#cruiseID", OleDbType.Int).Value = Convert.ToInt32(Route_Txt.Text)
Dim RCTable = new DataTable()
Dim reader = cmd.ExecuteReader()
reader.Load(RCTable)
At this point the RCTable is filled with the data coming from the two tables and selected using the Route_Txt textbox converted to an integer. If the CruiseID field is not a numeric field then you should create the parameter as of type OleDbType.VarWChar and remove the conversion to integer
Try simplifying your query.
Dim CruiseRouteQuery As String = "SELECT C.CruiseID, C.RoutID, R.Routename FROM Cruise C LEFT JOIN Route R ON C.RouteID = R.RoutID WHERE CruiseID =?"
Also, please let us know what errors you are getting.

SELECT statement with JOIN and WHERE clause not returning any data

I have problem with data that needs to be seen on datagridview. Bellow is my code:
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CONNECT_STRING As String = (...)
Dim cnn As New OleDbConnection(CONNECT_STRING)
cnn.Open()
MsgBox(status_narocila.value)
Dim sql As String = "SELECT artikel.st_artikla, artikel.naziv_artikla, narocilo.kolicina, narocilo.barva_tiska, narocilo.izvedba, narocilo.opombe, narocilo.datum_narocila, narocilo.rok_izdelave, narocilo.status, narocilo.ID FROM (narocilo INNER JOIN artikel ON narocilo.id_artkla = artikel.ID) WHERE(narocilo.ID = '" & status_narocila.value & "')"
Dim cmd As New OleDbCommand(sql, cnn)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds, "artikel")
cnn.Close()
DataGridView1.DataSource = ds.Tables("artikel")
End Sub
End Class
Value status.narocila.value is integer, I've tested it and getting right value from it. The code is working fine without WHERE clause.
= '" & status_narocila.value & "')"
should be
= " & status_narocila.value & ")"
no ' on numeric data types.
If narocilo.ID is also an integer, then the problem is you're using text qualifers on an integer field.
Try changing your WHERE clause to:
WHERE(narocilo.ID = " & status_narocila.value & ")"

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.