Ok, hopefully I explain this correctly. I have had about 3 months professional experience working with Access databases, and none with Vb.net, but I am working on a project to get my degree. The goal of this project was to create a Windows Form for my parent's company, All Keyed Up Lock & Safe.
This form was going to link to an Access database with 4 tables that was a listing of some of the company's customers. The form would then allow you to search that database for a specific customer and then return all the information on that specific customer.
This would be useful for billing and also would let us view any special notes we have on the customer before leaving. The four tables are [McDonald's-Corporate Stores], [McDonald's-Independently Owned], [Sonic-Corporate Stores], [Sonic-Independently Owned].
Basically the problem I am having is with the search function. I cannot for the life of me figure out a way to get this to work. I have tried 4 or 5 different solutions and still nothing. I am using Visual Studio 2013. Here is my code I have at the moment, for the search button:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim Connection As New SqlClient.SqlConnectionStringBuilder
Connection.DataSource = "file:///C:\Users\thelukester145\Documents\All%20Keyed%20Up\All%20Keyed%20Up,%20Lock%20&%20Safe,%20LLC.accdb"
Dim objSQLConnection = New SqlClient.SqlConnection(Connection.ConnectionString)
Dim cmd As New SqlCommand()
Dim myTable As New DataTable()
Dim SearchFor = SearchBox.Text
If AddressButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [Address] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
ElseIf NumberButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [McOpCo#] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
End If
DataGrid.Show()
End Sub
As you can see I have just been trying to get this to work for just one table and can't even do that. I would prefer not to use the datagrid method to display the information but rather display it in textboxes that are positioned on the form.
Anyways any help would be MUCH appreciated and sorry for such a long question.
Where are you opening the connection. Can you try the following code to establish a connection:
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\URDataBaseName.mdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
' your code goes here
cnnOLEDB.Close()
Related
how can I possibly populate my table if like textbox.text matches from my data inside database.
I'm stuck here, not sure where I did go wrong
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim dbcommand As String
dbcommand = "SELECT * FROM aws_rdp where csn_user like " & txtCSNUser.Text & ""
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub
Try putting ' before and after the quotation marks surrounding the textbox text. If you're trying to find that text within the text stored in the database you will also need wildcards (%) surrounding it too. Try:
dbcommand = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Also, as others have stated, look into using parameters in your SQL code as it will help prevent things like SQL injection and is always good practice
Found the answer to my problem by using this code. Anyways, thanks for your time replying on my query, will surely take note of your advises for my future references
Dim dbcommand As String = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Dim command As New OleDbCommand(dbcommand, dbconn)
Dim adapter As New OleDbDataAdapter(command)
Dim datatable As New DataTable
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(1).HeaderText = "IP Address"
DataGridView1.Columns(2).HeaderText = "Username"
DataGridView1.Columns(3).HeaderText = "Password"
I have a list of client names, project names, employee names, and hourly rates in an OpenOffice spreadsheet that I need to import to Visual Basic .net 2017. It would be preferred if I could do this to a combo box, so the user can just select the names from a drop-down list. It seems as if this is impossible without setting up an SQL server. Does anyone know how I should go about doing this?
I've tried this but it says that it can't connect to Microsoft.Ace.OLEDB.12.0
I got this code from a YouTube video
Private Sub btnGetSpread_Click(sender As Object, e As EventArgs) Handles btnGetSpread.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "P:\Coding\Visual Studio\Visual Basic\TestProject\TestProject\bin\Files\Company_Sheet.ods"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source =" + "P:\Coding\Visual Studio\Visual Basic\TestProject\TestProject\bin\Files\Company_Sheet.ods" + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
dgvSpread.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
This will get you started. I sometimes have to import data from Excel spreadsheets into an Oracle database, this code is years old, but still works (VS 2013). Modify to suit your situation.
Dim sourceFile As String = "C:\Users\appdata\Documents\SomeData.xls"
Dim srcConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourceFile & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Dim srcConn As OleDbConnection = New OleDbConnection(srcConnString)
srcConn.Open()
' in the select statement, the fields are the column names in the spreadsheet and are expected to be in row 1 and are case sensitive
' the from clause in the query is the tab of the spreadsheet where the data is
Dim cmdExcel As OleDbCommand = New OleDbCommand("Select NAME,ADDRESS,CITY,STATE,ZIP From [DATA$] Where some where clause", srcConn)
Dim drExcel As OleDbDataReader = cmdExcel.ExecuteReader()
' Now loop through the rows in the spreadsheet
While drExcel.Read()
'Do stuff ...
End While
Private Function CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection) As OleDbDataAdapter
// Initiating instances for the function
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim myCommand As OleDbCommand
Dim parameter As OleDbParameter
// establishing the string to tell where to delete record from and how to find the record i want.
// PlayerIDTextBox.Text is a text on a form that is populated from the database after selecting a list of name (this works correctly) // connection is already open and is directed to correct place
Dim sql As String = "DELETE * FROM Players WHERE ID ='" & CInt(PlayerIDTextBox.Text) & "'"
myCommand = New OleDbCommand(sql, playerDBconnection)
parameter = myCommand.Parameters.Add("ID", OleDbType.Char, 3, "ID")
parameter.SourceVersion = DataRowVersion.Original
dataAdapter.DeleteCommand = myCommand
Return dataAdapter
End Function
// i call this function after executing a button click.
//ListPlayerComboBox.Text is populated with the names and needs it a name to fill PlayerIDTextBox.Text(works correctly)
Private Sub RemovePlayerButton_Click(sender As System.Object, e As System.EventArgs) Handles RemovePlayerButton.Click
If ListPlayerComboBox.Text = " " Then
MsgBox("Please Select a Player.")
Else
Me.CreatePlayerAdapter(playerDBConnection)
End If
End Sub
// no errors occur. However, nothing is done in the database. help please?
Notes:
1)Never leave your OleDbConnection Open. Only allow it to be opened when you actually need it. This will save you from a lot of headaches later on. The reasons why can be found on following stackoverflow question.
2) There is no reason to return an OleDbDataAdapter if you don't intend on using it.
3) Use your parameters correctly : see below example2
4) Keep in mind that there are some restricted keywords in Access. Luckely for you ID isn't one. The restrictedKeywords can be found here: Keywords
I'm probably missing some further points here. Anyone should be free to add em.
Why not adjust your Function CreatePlayerAdapter to the following:
1) Without parameters
Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection)
Dim myCommand As OleDbCommand
Dim sql As String = "DELETE * FROM Players WHERE ID =" & CInt(PlayerIDTextBox.Text)
myCommand = New OleDbCommand(sql, playerDBconnection)
playerDBconnection.Open()
myCommand.ExecuteNonQuery()
playerDBconnection.Close()
End Sub
2) With parameters
Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection)
Dim myCommand As OleDbCommand
Dim sql As String = "DELETE * FROM Players WHERE ID = #playerId"
myCommand = New OleDbCommand(sql, playerDBconnection)
Dim param As New OleDb.OleDbParameter(#playerId", CInt(PlayerIDTextBox.Text))
myCommand.Add(param)
playerDBconnection.Open()
myCommand.ExecuteNonQuery()
playerDBconnection.Close()
End Sub
The method ExecuteNonQuery executes the query passed to the command on the specified OleDbConnection and returns the number of rows affected. More info Here
still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub
My name is Sarfaraz. I am developing a project in VB.Net and MSAccess 2007. I have a listbox control that is being populated from a table in Access called items. I am using a combination of two listbox's to select differnt values. I want to get the rate of the individual item when I hit the save button. The values are stored in a clients table. I am storing the data like Sugar=5 Biscuits=10 etc.
I am using a VB6 textbox and Recordset and need to know how I would implement the same thing in VB.Net
I have figured the answer but it is taking a very long time to perform the task and my system is going in a busy mode for almost 10 seconds. Is there anything wrong in this code Please have a look
Thank you.
Here is my code
Con.Open()
For l_index = 0 To ListBox2.Items.Count - 1
query = ("select Investigation.rate " & _
"from Investigation WHERE (((Investigation.Investigation) = '" & ListBox2.Items(l_index) & "'));")
Dim cmd2 As New OleDbCommand(query, Con)
'Con.Open()
Dim reader As OleDbDataReader = cmd2.ExecuteReader
reader.Read()
'Console.WriteLine(reader(0))
txtrate.Text = reader.GetString(0)
reader.Close()
'Con.Close()
' Con.Close()
'End If
Dim SqlString As String = "Insert Into patients (Receipt_No, OPD_MRD,Patientname,Investigation,Receipt_date,Receipt_time,rate) Values (?,?,?,?,?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, Con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("Receipt_No", txtreceiptno.Text.Trim())
cmd.Parameters.AddWithValue("OPD_MRD", txtopd.Text.Trim())
cmd.Parameters.AddWithValue("Patientname", txtname.Text.Trim())
cmd.Parameters.AddWithValue("Investigation", CStr(ListBox2.Items(l_index)).ToString())
cmd.Parameters.AddWithValue("Receipt_date", lbldate.Text)
cmd.Parameters.AddWithValue("Receipt_time", lbltime.Text)
cmd.Parameters.AddWithValue("rate", txtrate.Text.Trim())
'Con.Open()
cmd.ExecuteNonQuery()
Next
Con.Close()