For a Windows desktop VB.NET application, I am trying to invoke auto suggest only when user type 3 letters or more. The database contains thousands of rows and I do not want to load all of them on form load. I want to only get from database when needed and for items matching first few letters.
So far I have
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If Len(TextBox1.Text) >= 3 Then
'invoke autosuggest
End If
End Sub
Then not sure how to invoke autosuggest so that user would not have to type the full text, my query would be something like:
Select Fullname, email from Contact where fullname like & textbox1.text order by full name
Any direction or code suggestion would be greatly appreciated.
You can change your query as :
Dim cmd As SqlCommand
Dim con As SqlConnection ='your connexion string here
Dim csql As String = "Select Fullname, email from Contact where fullname like #SEARCH order by full name"
cmd = New SqlCommand(csql, con)
cmd.Parameters.AddWithValue("#SEARCH", "'" + TextBox1.Test + "%'")
cmd.ExecuteNonQuery()
an dalso use
If TextBox1.Text.Length >3 Then
'invoke autosuggest
End If
instead of
If Len(TextBox1.Text) >= 3 Then
'invoke autosuggest
End If
Related
I'm trying to insert data into a database with an autonumber in MS Access as primary key. I get an error saying "Number of query values and destination fields are not the same. The data types in MS Access are Autonumber (I didn't include it in the INSERT statement), String (#OrderNo), String (#Product), Number (#Qty), and Date (#TDate). Here's the image:
Here's my code:
For Each row As DataGridViewRow In DataGridView1.Rows
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Inventory.accdb;"
Using conn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert into Table1 Values(#OrderNo, #Product, #Qty, #TDate)", conn)
cmd.Parameters.AddWithValue("#OrderNo", TxtOrder.Text.ToString)
cmd.Parameters.AddWithValue("#Product", row.Cells("Product").Value)
cmd.Parameters.AddWithValue("#Qty", row.Cells("Qty").Value)
cmd.Parameters.AddWithValue("#TDate", Date.Now.ToString("MM/dd/yyyy"))
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
You need to change your sql to "Insert into Table1 (OrderNo,Product,Qty,TDate) Values(#OrderNo, #Product, #Qty, #TDate)".
The following code works for me.
DataGridView1.AllowUserToAddRows = False
For Each row As DataGridViewRow In DataGridView1.Rows
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=...;"
Using conn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert into Table1 (OrderNo,Product,Qty,TDate) Values(#OrderNo, #Product, #Qty, #TDate)", conn)
cmd.Parameters.AddWithValue("#OrderNo", TxtOrder.Text.ToString)
cmd.Parameters.AddWithValue("#Product", row.Cells("Product").Value)
cmd.Parameters.AddWithValue("#Qty", row.Cells("Qty").Value)
cmd.Parameters.AddWithValue("#TDate", Date.Now.ToString("MM/dd/yyyy"))
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
Well, I think we dealing with a bit of a chicken and a egg problem here?
I mean, how did the grid get created?
How and where did you setup the columns in the grid?
lets drop a data grid view into a form. Drop in a button.
We have this code to load up the grid:
Private Sub HotelGridEdit_Load(sender As Object, e As EventArgs) Handles Me.Load
LoadGrid()
End Sub
Sub LoadGrid()
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"SELECT ID, FirstName, LastName, City, HotelName, Description, Active FROM tblHotelsA
ORDER BY HotelName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
DataGridView1.DataSource = rstData
End Using
End Using
End Sub
So, now we have this:
Now, in a above, I can cursor around - make any edits I want.
I can also type in on the bottom blank row to add new rows.
I can click on the left side recordselector, and hit delete key.
Now, to save my edits, save my addtitions, and save my deletes?
I have the one button at the top, and this code works to do all updates, all addtitions, and all deletes.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' save all edits, and new rows, and deletes
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"SELECT ID, FirstName, LastName, City, HotelName, Description, Active FROM tblHotelsA"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim da As New OleDbDataAdapter(cmdSQL)
Dim daC As New OleDbCommandBuilder(da)
da.Update(DataGridView1.DataSource)
End Using
End Using
End Sub
So, not a lot of code.
In fact, often using a data table is a lot less work, since you don't have to mess with all those parameters anyway - even if your data grid was somehow not feed from the database. But, if you feeding the "grid" from the database, then really, you can just add rows - and then write some code to send the changes back to the database with the above code. And if you want to start out with a blank grid - not show previous rows, then just add to your sql like this:
SELECT * from tblHotels WHERE ID = 0 Order by Hotelname
Use above to create a data table without any rows but STILL bind that to the grid, and thus once again, to add, or delete rows, you just edit and add them, and again the SAME code I had above will work to save edits, deletes and additions.
Hi I'm trying to display a selected product on a listbox similar in this video:
https://www.youtube.com/watch?v=QbbZzaMZGhY
In the video, when he click an item from the listbox, its values appear(price and name) on the textbox. I reviewed the source code but he was not using a database. In my case, I need to use an access database to list all of my product and their id and price. Here's what I got so far from asking here:
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
Dim prodidparam As New OleDbParameter("#productid", Me.txtproductid.Text)
Dim prodparam As New OleDbParameter("#product", Me.txtproduct.Text)
Dim priceparam As New OleDbParameter("#price", Me.txtprice.Text)
lbcmd.Parameters.Add(prodidparam)
lbcmd.Parameters.Add(prodparam)
lbcmd.Parameters.Add(priceparam)
'Open the connection
lbconn.Open()
txtproduct.Text = listboxitems.SelectedItem
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetString("price").ToString()
End While
End Using
End Using
End Using
End Sub
In the line:
txtproduct.Text = listboxitems.SelectedItem
I managed to show its name in the textbox, but its not coming from my database. I can't just type their price and name in the project but I need my data source to come from the database. So far nothing is showing up in the app. What am i missing? Thanks.
EDIT: The form load code where the listbox is filled with the database.
Private Sub shop_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Create a connection to the database
provider = "PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source="
datafile = "C:\Users\USER PC\Desktop\orderDB1.accdb"
connString = provider & datafile
myConnection.ConnectionString = connString
'Open the connection with error handling
Try
If Not myConnection.State = ConnectionState.Open Then
End If
myConnection.Open()
Catch OleDbExceptionErr As OleDbException
MessageBox.Show(OleDbExceptionErr.Message)
Catch InvalidOperationErr As InvalidOperationException
MessageBox.Show(InvalidOperationErr.Message)
End Try
'Command Object. Select from productlog. 'productlog name of table'
Dim objcmd As New OleDbCommand("SELECT * FROM productlog", myConnection)
'data adapter and data table.
Dim da As New OleDbDataAdapter(objcmd)
Dim dt As New DataTable("productlog")
da.Fill(dt)
'Create connection and release resources
myConnection.Close()
myConnection.Dispose()
myConnection = Nothing
objcmd.Dispose()
objcmd = Nothing
da.Dispose()
da = Nothing
'fill from access to the listbox
For Each row As DataRow In dt.Rows
listboxitems.Items.Add(row.Item("product"))
Next
'Release resources
dt.Dispose()
dt = Nothing
End Sub
EDIT: CODE UPDATED
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE product = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
Dim prodparam As New OleDbParameter("#product", listboxitems.SelectedItem)
Dim prodidparam As New OleDbParameter("#productid", listboxitems.SelectedItem)
Dim prodpriceparam As New OleDbParameter("#price", listboxitems.SelectedItem)
lbcmd.Parameters.Add(prodparam)
lbcmd.Parameters.Add(prodidparam)
lbcmd.Parameters.Add(prodpriceparam)
'Open the connection
lbconn.Open()
txtproduct.Text = listboxitems.SelectedItem
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = listboxitems.SelectedItem.ToString()' iknow im missing alot in this line of code i just dont know what that is'
txtproduct.Text = listboxitems.SelectedItem.ToString()
txtprice.Text = listboxitems.SelectedItem.ToString()
End While
End Using
End Using
End Using
End Sub
I changed the get statements cause im having an error that says cannot convert type integer to string. im sorry if im making this really hard stack overflow is like my first line of defense and my last resort at the same time.
Your query is wrong. You want to get back the productid, product and price from the productlog table WHERE the record searched is equal to the productid, product and price that you supply as parameters.
Did you see the problem?
If you already know these values why ask the database? I suppose that your task is to find the product and price given the product stored in the current list item. If so, there is no need to use the textboxes and your query should be
SELECT productid, product, price FROM productlog WHERE product = ?
And the parameter is the data extracted by the listbox item
Dim prodidparam As New OleDbParameter("#product", listboxitems.SelectedItem)
Now your code could reach the while loop and set the textboxes with the missing informations. Of course this works because you have distinct product names in your table (meaning, there are no two records with the same product name)
EDIT
Looking at your comments below it seems that you are really confused how to use the GetPos, GetString, GetInt32 and eventually GetDecimal.
Once you have called lbreader.Read() you have a record at your disposition to transfer into your textboxes. But there is little point to take in consideration. You should call the various GetXXXX appropriate for the datatype of the underlying column. This problem is often overlooked by VB.NET programmers used to the automatic type conversion applied by the VB.NET compiler. These conversions don't exist in the lower levels of NET and it is better to avoid these conversions at all to not fall in subtle problems.
However, to call a OleDbDatareader.GetXXXX you need the ordinal position of the field in the returned record. So you need to call first OleDbDataReader.GetPos and then use the value returned by GetPos to extract the info from the GetXXXXX call.
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
Dim pos = lbreader.GetPos("product")
txtProduct.Text = lbreader.GetString(pos)
pos = lbreader.GetPos("productid")
txtProductID.Text = lbreader.GetInt32(pos).ToString()
pos = lbreader.GetPos("Price")
txtPrice.Text = lbreader.GetDecimal(pos).ToString()
End While
End Using
The last line uses GetDecimal assuming the column Price to be a numeric decimal in your database (as it should being it a currency value), if not, then use the appropriate GetXXXXX. Note also that the two last GetXXXX returns an Int32 and a Decimal. To assign these values to a property of type string (like Text) you should use an explicit conversion to a string (ToString())
First question here, and forewarning I am very new to programming in general, just trying to figure the basics out.
Basically what I am trying to do is select all items in a specified list from my SQL server, add them to an array and then fill a combobox with that array.
The SQL server structure is as follows:
Just a representation
The user will select which product they are building when they log in, and then I would like a combobox to be filled with all of the parts that pertain to that item.
The current code sample
Public Class frmProduct
Private Sub frmProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim mycon As SqlConnection = New SqlConnection('connection string')
mycon.Open()
Using mycon
Dim prodlist As String = frmMain.cmbProduct.SelectedItem
Dim cmds As String = "SELECT DISTINCT(Product) FROM [Products] where Product = #prodlist"
Dim cmde As New SqlCommand(sqlt, mycon)
cmde.Parameters.AddWithValue("#Product", prodlist)
Dim dr As SqlDataReader = scmd.ExecuteReader
If dr.HasRows() Then
cmbFailure.Items.Add(dr.GetString(0))
End If
scmd.ExecuteNonQuery()
End Using
End Sub
End Class
The user selects the Product on the login form, and the selected product is carried over to the parts list form.
The error I am currently recieving which is likely the first of many is "Invalid Column Name Product". I thought that the issue might be that the selected product is not carrying over, but I added a label which I am changing the text to be equal to "prodlist" and it accurately changes the label text.
Again I am fresh meat at all of this, so I apologize for any obvious blunders. Thank you for your help!
In the image you attached the "Product1, Product2, Product3" are fixed columns?
If are, you have to use these columns in your select statement. This is a bad design but will work.
I assume that's a study exercise, so later, can you enhance your project adding 2 tables, one for products and other for store parts of products.
For information about the code.
Private Sub frmProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim mycon As SqlConnection = New SqlConnection('connection string')
Dim cmds As String = "SELECT DISTINCT(Product) FROM [Products] where Product = #prodlist"
Try
' Most of the DB will having a connection fail, so programmer must set a try catch for it '
mycon.Open()
Using mycon
Dim prodlist As String = [Form].[ComBoBox].SelectedItem
Dim cmde As New SqlCommand(sqlt, mycon)
cmde.Parameters.AddWithValue("#Product", prodlist)
Dim dr As SqlDataReader = scmd.ExecuteReader
If dr.HasRows() Then
cmbFailure.Items.Add(dr.GetString(0))
End If
scmd.ExecuteNonQuery()
' For more save for this sql will execute successfully, some of programmer will use Transaction with commit '
' Microsoft Link: https://msdn.microsoft.com/en-us/library/5ha4240h(v=vs.110).aspx '
End Using
' mycon.Close() '
Catch ex As Exception
MessageBox.Show(ex.Message) ' Exception Message '
' [Optional]Release object '
' mycon.Close() '
End Try
End Sub
And for your items with it may crash the result, due to scmd was not same as cmde.
Would you please explain [scmd] is stand for?
When a user selects a client from combobox 1 (a company we do work with and are partners with), its supposed to populate the users from combobox 2 for that client only, which needs to come from that particular database in SQL Server.
Example:
The first Combobox with all the Clients when a user selects a client and the Second ComboBox with all the Users from that database only, I want the Users list of the Second ComboBox to change according to the Clients selected from the list of the first ComboBox, but including a connection string, via SQL Server.
So if I select say....Google in Combobox 1 and in Combobox 2, I expect say.....10 users from Google. But if I change my mind and select Yahoo in Combobox 1 and in Combobox 2, I expect say..... this time around 12 users from Yahoo.
Database Name I'm using: MyDatabase
Get the users from these databases, based on the selection I make, which contains those particular users, not MyDatabase which has users as well:
GoogleQA (If user selected Google, get the users from this database only and populate it during runtime)
YahooQA (If user selected Yahoo, get the users from this database only and populate it during runtime)
My VB.Net code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
Dim cmd As New SqlCommand("Select * from CLIENTS", con)
con.Open()
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
con.Close()
cboClient.DataSource = dt
cboClient.DisplayMember = "CLIENT_NAME"
cboClient.ValueMember = "ID"
rtfMessage.Tag = "Enter your message here"
rtfMessage.Text = CStr(rtfMessage.Tag)
What can I put in my comboboxes code to get the end goal of what I want to happen:
Private Sub cboUser_SelectedValueChanged(sender As Object, e As EventArgs) Handles cboUser.SelectedValueChanged
--What do I put here?
End Sub
Private Sub cboClient_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboClient.SelectedIndexChanged
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr2").ConnectionString)
Dim cmd As New SqlCommand("Select * from USERS", con)
con.Open()
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
con.Close()
cboClient.DataSource = dt
cboClient.DisplayMember = "NetworkID"
cboClient.ValueMember = "ID"
cboClient.Text = ""
If cboClient.SelectedItem.Text = "Sunoco" Then
cboUser.Items.Add("NetworkID")
End If
End Sub
Possibility: On client change combo box function (cboClient_SelectedValueChanged)
1.) Change the database connection
2.) Query the proper user data from the correct database
3.) populate the user combo box with that user data
You just do what you have done in the load section in an if statement inside your user section.
sort of like :
`If cboClient.SelectedItem.Text = "Google" then
(code to populate the other combobox with google info)
End if`
`If cboClient.SelectedItem.Text = "Yahoo" then
dim sql as string = "Select firstName+ " " +lastname as empName from
Yahoo table"
dim cmd as sqladapter(sql, con)
dim dt as datatable
cmd.fill(dt)
cboUsers.datasource = dt
cboUsers.Datatextfield = "empName"
cboUsers.Datavaluefield = "empName"
cboUsers.DataBind()
End if
Dim sql2 As String = "Select EQPnumber, EQPdesc from CREW_LINEUP_ACTIVE_EQUIPMENT"
Dim activeEQPadt As New SqlDataAdapter(sql2, IPMS.Settings.conn)
activeEQPadt.Fill(activeDT)
ActiveEQPLstBx.DataSource = activeDT
ActiveEQPLstBx.DataTextField = "EQPdesc"
ActiveEQPLstBx.DataValueField = "EQPnumber"
ActiveEQPLstBx.DataBind()
my question is the following:
i have 2 tables created in access and created a form in vb net.
The first table consists of: Id(primary key),first name,lastname.
thes second table contains the visits and it consists of:visitID,DateOfVisit.
My question is how to join these two tables so that each ID fron the first table when selected to display the correspodind row from the second table..
For example one ID can have surname and lastname and 1 or more dates that are stored in the second table..
When i search for name it fills only the firstname and the lastname but not the date.This is where i have stuck.I want when i search with the name to also fill the correspoding textbox or display in a grid the dates that the selected record has.
Thanks.
Imports System.Data.OleDb
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DoctorDataSet.Table1' table. You can move, or remove it, as needed.
Me.Table1TableAdapter.Fill(Me.DoctorDataSet.Table1)
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Desktop\Desktop\doctor.accdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Private Sub FindButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindButton.Click
myConnection.Open()
FirstnameTextBox.Clear()
LastnameTextBox.Clear()
VisitsTextBox.Clear()
Dim str As String
str = "SELECT * FROM table1 WHERE (Firstname = '" & CodeText.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
FirstnameTextBox.Text = dr("Firstname").ToString
LastnameTextBox.Text = dr("Lastname").ToString
VisitsTextBox.Text = dr("Visits").ToString
End While
myConnection.Close()
End Sub
Private Sub Table1BindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Table1BindingNavigatorSaveItem.Click
Me.Validate()
Me.Table1BindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DoctorDataSet)
End Sub
Private Sub BindingNavigatorMovePreviousItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorMovePreviousItem.Click
End Sub
End Class
I attach the full code as well as the database and a screenshot from the prgoramm.everything works well when i search,but as you can see i have also one more table(table2) which contains the number of appointments for each id from table1.Thats where i have stuck,i cant get this to work ..for example id from table1 apart from the info for name and surnames to also display and the number of visits.
I hope i am more clear now..:)
ps: i am new in vbnet and only started a few days ago programming in that language.
Ok just forget what i wrote i will try to put it in another way...
These are my 2 tables:
Table1 for customers,first column is for the id of each one which is unique,then the firstname and second name follow.
ID Firstname SecondName
1 John Jones
2 James Jameson
3 Nick Patrick
4 Nicky Summers
Table2 is for storing the date of visit.Each ID from table1 can have 0 or more visits.In that case only the third(Nick Patrick) in null.
ID Visit_Date
1 1/1/2010
2 5/1/2012
3 -
4 7/1/2014
I have created the database in access and load it on my project in visual studio.When I drag and drop the boxes from my datasource from the right column into the form I have one textbox for id,one for firstname,one for secondname and one for visitdate.
The navigation bar is placed on the top.when I press the next button all the fields are filled apart from the visit_date textbox which displays the first record always.
This should be the answer to your problem.
You can't join the 2 tables unless they both have a common field. So your 2nd table should have an ID field too and should not be a primary key. Then you can use this SQL statement.
"SELECT table1.ID, table1.firstname, table1.lastname, table2.visitID, table2.dateofvisit FROM table1 INNER JOIN table2 ON table1.ID=table2.ID WHERE table1.ID='" & ID & "'"
where ID is the variable name which holds the ID of a person. You shouldn't be using the FirstName field for the WHERE clause since it is possible that people have the same first names. Use the unique field among all the fields...which in this case is the ID field.