How to take data from access data to Combobox - vb.net

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

Related

How to update access db by editing datagridview cells?

Im trying to edit items after inserting to access by clicking the save button? How can i save the edits done in datagridview rows to access?
Already tried the update query
For each loop
vb.net
Private Sub BunifuFlatButton1_Click(sender As Object, e As EventArgs) Handles BunifuFlatButton1.Click
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb")
Dim conn As New OleDbConnection(constring)
For Each row As DataGridViewRow In DataGridView1.Rows
Using con As New OleDbConnection(constring)
'nettxt.Text = (grosstxt.Text * perdistxt.Text / 100) - (dislctxt.Text + disusd.Text + distax.Text)
Dim cmd As New OleDbCommand("Update PurchaseInvoice set [Itemnum] = #ItemNum, [Itemname]= #ItemName, [Itemqty]= #ItemQty, [Itemprice] = #ItemPrice, [discount] =#discount, [subtotal] = #subtotal,[Preference] = " & preftxt.Text & ", [Suppnum] = " & pnumtxt.Text & ", [UniqueID] = " & pautotxt.Text & " Where [UniqueID] = " & pautotxt.Text & "", con)
cmd.Parameters.AddWithValue("#ItemID", row.Cells("ItemID").Value)
cmd.Parameters.AddWithValue("#ItemName", row.Cells("ItemName").Value)
cmd.Parameters.AddWithValue("#ItemQty", row.Cells("ItemQty").Value)
cmd.Parameters.AddWithValue("#ItemPrice", row.Cells("ItemPrice").Value)
cmd.Parameters.AddWithValue("#discount", row.Cells("discount").Value)
cmd.Parameters.AddWithValue("#subtotal", row.Cells("subtotal").Value)
cmd.Parameters.AddWithValue("#Ref", preftxt.Text.ToString)
cmd.Parameters.AddWithValue("#Suppnum", Convert.ToInt32(pnumtxt.Text))
cmd.Parameters.AddWithValue("#UniqueID", Convert.ToInt32(pautotxt.Text))
DataGridView1.AllowUserToAddRows = False
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'This the code i used to show the data in datagridview:
Private Sub NewPurchaseInvoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb"
con.Open()
Dim sql As String = "Select [Itemnum],[Itemname],[Itemprice],[ItemQty],[discount],[subtotal] from PurchaseInvoice where [UniqueID] = " & pautotxt.Text & ""
Dim cmd10 As OleDbCommand = New OleDbCommand(Sql, con)
'Dim adap As New OleDbDataAdapter("Select [Itemnum],[Itemname],[Itemprice],[discount],[subtotal] from PurchaseInvoice where UniqueID = " & pautotxt.Text & "", con)
'Dim ds As New System.Data.DataSet
'adap.Fill(ds, "PurchaseInvoice")
Dim dr As OleDbDataReader = cmd10.ExecuteReader
Do While dr.Read()
DataGridView1.Rows.Add(dr("ItemNum"), dr("ItemName"), dr("ItemQty"), dr("ItemPrice"), dr("discount"), dr("subtotal"))
Loop
con.Close()
I expect that all the rows will be updated as each other, but the actual output is that each row has different qty name etc...
This code does not seem appropriate in the load event because pautotxt.Text will not have a value yet. Can you move it to a Button.Click?
I guessed that the datatype of ID is an Integer. You must first test if the the .Text property can be converted to an Integer. .TryParse does this. It returns a Boolean and fills IntID that was provided as the second parameter.
You can pass the connection string directly to the constructor of the connection. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. You can pass the Select statement and the connection directly to the constructor of the command.
ALWAYS use Parameters, never concatenate strings to avoid sql injection. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
The DataAdapter will open the connection, fiil the DataTable and close the connection if it finds it closed; however if it is found open it will leave it open.
The last line binds the grid to the DataTable.
Private Sub FillGrid()
If Not Integer.TryParse(pautotxt.Text, IntID) Then
MessageBox.Show("Please enter a number")
Return
End If
dt = New DataTable()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(Sql, con)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Dim adap = New OleDbDataAdapter(cmd)
adap.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
DataTables are very clever. When bound to a DataGridView they keep track of changes and mark rows as update, insert, or delete. The DataAdapter uses this info to update the database. Once the database is updated we call .AcceptChanges on the DataTable to clear the marking on the rows.
Private Sub UpdateDatabase()
Using cn As New OleDbConnection(ConnString)
Using da As New OleDbDataAdapter(Sql, cn)
da.SelectCommand.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Using builder As New OleDbCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
dt.AcceptChanges()
End Sub

Can't INSERT INTO access database

I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

populate listbox from sql db where 3 fields meet textbox values

I am trying to return rows in a listbox from a sql database. I only want the rows to be returned where 3 fields match textbox values. Currently, the listbox is returning ALL rows if ANYTHING is typed into any of the 3 textboxes. If nothing is typed in , nothing shows up (that part is the expected/correct behavior).
My code is:
Private Sub tireselect_Load(sender As Object, e As EventArgs) Handles MyBase.Load
m_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
m_cn.Open()
'Dim con As New SqlConnection()
'Dim cmd As String = "Select brand, model, width, aspect, rim, retail from dbo.tires"
Dim sqltext = "SELECT [ID] ,[brand] ,[model] ,[cost] ,[retail] ,[width] ,[aspect] ,[rim] FROM [tires].[dbo].[tires]"
Using sqlCon = New SqlConnection("Data Source=localhost;Initial Catalog=tires;Integrated Security=True")
sqlCon.Open()
Dim cmd = New SqlCommand(sqltext, sqlCon)
cmd.Parameters.AddWithValue("#tirewidth", (Int(TireLookup.txtWidth.Text)))
cmd.Parameters.AddWithValue("#tireaspect", (Int(TireLookup.txtAspect.Text)))
cmd.Parameters.AddWithValue("#tirerim", (Int(TireLookup.txtRim.Text)))
cmd.ExecuteNonQuery()
End Using
Dim m_da As New SqlDataAdapter("SELECT [ID] ,[brand] ,[model] ,[cost] ,[retail] ,[width] ,[aspect] ,[rim] FROM [tires].[dbo].[tires] where [width]=tirelookup.txtwidth.text AND [aspect]=tirelookup.txtwidth.text AND [rim]=tirelookup.txtrim.text", m_cn)
Dim myDataSet As New DataSet()
m_da.Fill(myDataSet, "dbo.tires")
Dim myDataTable As DataTable = myDataSet.Tables(0)
Dim tempRow As DataRow
For Each tempRow In myDataTable.Rows
ListBox1.Items.Add(tempRow("brand"))
ListBox2.Items.Add(tempRow("model"))
ListBox3.Items.Add(tempRow("width") & " / " & tempRow("aspect") & " / " & tempRow("rim"))
ListBox4.Items.Add("$ " & tempRow("retail") & " Tire ID=" & (tempRow("ID") - 1))
Next
End Sub
You need to change your predicates like this:
where [width]=#tirewidth
AND [aspect]=#tireaspect
AND [rim]=#tirerim

populate a combobox using a selection in another combobox from excel sheet

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 & "'"