I am coding in vb on visual studio 2012 and I need to create a query that pulls table data into a datagriddview. I have a textbox for user input and a combobox to set what the column name. Sort of like, "SELECT * FROM TITLES WHERE COMBOBOX LIKE TEXTBOX". I apologize if this question is old ground for you but I looked everywhere and couldn't find what I was looking for. Also I am a total newb so please speak slowly and in small words. Thanks in advance for your help.
You need to modify your SQL to be:
"SELECT * FROM TITLES WHERE " & ComboBox1.Text & " LIKE '%" & TextBox1.Text & "%'"
Deja Vu's answer should be ok. You may take it a step further, and try using a parameter instead of building the sql string directly from users' direct input, thus avoiding SQL Injection (which is a security risk):
Dim Sql As String = "SELECT * FROM MYTABLE WHERE " & ComboBox1.Text & " LIKE '%?%' "
Dim p As New OleDb.OleDbParameter : p.Value = Textbox1.text
Dim OleDBCommand As New OleDb.OleDbCommand(Sql, Connection)
OleDBCommand.Parameters.Add(p)
Dim da As New OleDb.OleDbDataAdapter(OleDBCommand)
Dim DT As New DataTable
da.Fill(DT)
(Note: I'm assuming this is an Application and users must choose an item from the combobox, and they cannot change the content of the combobox.)
Related
I am creating an attendance management system in vb.net and using MS access as my database. I created a leave form in which the student on leave has a roll number and his details along with the from date and to date field.
What I'm trying to do is to show all the roll numbers of students in the ComboBox on leave if the DateTimePicker value is in between the to date and from date, the command that I created as MS access query is selecting the from date and to date ie., extreme dates matching with the DateTimePicker value but not showing the values if date is between the to and from date.
this is the code and query:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Open()
Dim cmd1 As New OleDbCommand("Select roll_no From leaves Where semester= " + ComboBox3.SelectedItem + " and (from_date<= #" & DateTimePicker1.Value.ToShortDateString & "# and to_date >= #" & DateTimePicker1.Value.ToShortDateString & "#)", con)
Dim da1 As New OleDbDataAdapter
da1.SelectCommand = cmd1
Dim dt1 As New DataTable
dt1.Clear()
da1.Fill(dt1)
ComboBox4.DataSource = dt1
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
con.Close()
End Sub
Is there any modification in query through which I can get my desired results to get all the roll no if DateTimePicker value is between dates in database?
Well, you probably do want to wrap the code in a using block - that way if you have a error, it will STILL close the connection. Also, it means you don't have to close the connection - a using block ALWAYS will (so, this costs you ONLY one extra line of code, but it more robust - will not leave stray connections open.
Next up:
While everyone warns and suggests to try and avoid string concertation for reasons of SQL injection?
Actually, the BETTER case is that string concatenation is tricky, messy, and you have to remember to use quotes to surround strings, maybe "#" for dates, and for numbers no surrounding delimiters. And one tiny missing single quote or whatever, and your sql is now wrong. So, this is a BETTER case and reason to use parameters - to allow you to write code, and write code that is easer to fix, read, maintain, and even add more parameters to without complex string concatenations.
So, I would suggest this:
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"Select roll_no From leaves Where from_date >= #cboDate and to_date <= #cboDate " &
"AND semester = #Semester"
Using cmd = New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#cboDate", OleDbType.DBDate).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Semester", OleDbType.Integer).Value = ComboBox3.SelectedValue
conn.Open()
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
ComboBox4.DataSource = cmd.ExecuteReader
End Using
End Using
And note how I dumped the need for a data adaptor - don't' need it.
And note how I dumped the need for a data table - don't' need it.
However, you do OH SO VERY often need a data table. So, since we humans do things over and over without thinking - memory muscle - then I would suggest that it is ok to create and fill a data table and shove that into the "on leave".
So since we "often" will need a data table, then for the sake of learning, then you could write it this way (so we now learn how to fill a data table).
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"Select roll_no From leaves Where from_date >= #cboDate and to_date <= #cboDate " &
"AND semester = #Semester"
Using cmd = New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#cboDate", OleDbType.DBDate).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Semester", OleDbType.Integer).Value = ComboBox3.SelectedValue
conn.Open()
Dim dt1 As New DataTable
dt1.Load(cmd.ExecuteReader)
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
ComboBox4.DataSource = dt1
End Using
End Using
But, either way? Note how I did not have to remember, think about, worry about, and try to figure out the delimiters. Is that a " # " we need for dates, or is that a " ' " we need around the date?
Of course this code would be placed in the timepicker value changed event.
I am attempting to create a process scheduler as a project in school this summer and am quite new to using VB. Currently I have a combobox bound to the "EmployeeBindingSource" which holds information for every single employee in a company. Each employee is assigned a skill level for each work station in the building. What I would like to do is if an employee is listed as having "0" skill in say, the assembly station, when selecting an employee to assign to the assembly station, that particular employee will not appear in the combobox.
From doing some research I believe that rather than binding the combobox to the data source in the designer, I will have to assign values to the each combo box in the code on a form load.
This is the access table that holds all the employee information
In the table we can see that Steve has a skill level of "0" in the AS_Level category (assembly).
However, here we can see that he still appears as an option for the assembly area when creating a new project
Currently all the data binding happens in the designer for each combo box and therefore no code has been written for the data binding. At the moment each combo box is bound to the "Full_Name" column in the access table.
Again, I am quite new to VB so I apologize if this is too vague. Let me know if I can give any more helpful information. Thank you all in advance.
After adding the code suggested here is what I have
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
datafile = "C:\Users\Jacob\Desktop\Halton\HaltonProject.accdb"
connString = provider & datafile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM [Employee] WHERE (SP_Level <> '" & 0 & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userfound As Boolean = False
Dim Full_Name As String
While dr.Read
userfound = True
Full_Name = dr("Full_Name").ToString
SP_Emp1.Items.Add(Full_Name)
SP_Emp2.Items.Add(Full_Name)
SP_Emp3.Items.Add(Full_Name)
SP_Emp4.Items.Add(Full_Name)
End While
myConnection.Close()
Works completely now!
Based on your comments and post, I assume, the checkboxes on the left enable/disable the comboboxes on that row, and since you're binding them individually if you change your query so it looks like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Employee] WHERE AS_Level <> 0 , myConnection) Dim dr As OleDbDataReader = cmd.ExecuteReader
Note that the where clause will vary depending on your needs, so it could be WHERE AS_Level <> 0 or WHERE SP_Level <> 0 and so on.
I have never used an Ole database so I'm not quite sure about the syntax, hope this helps.
Edit: For anyone facing this problem, don't miss the tips about only using
parameters instead of inserting the values directly into the SQL queries.
i'm facing a big problem with my vb.net project, i'm stuck with this for a week
i've a combobox item that i need to compare with an access number which is my database to retrieve some information, but i just got an error, no matter what format i convert my combobox item, it says my datatype is inconpatible with the expression
Here's one of the SQL queries from my code:
Dim dt1 As New DataTable
'This query select some itens from a row that match with the selected combobox number
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number," _
& " Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE" _
& " WHERE Number ='" & CInt(mycombobox.SelectedItem) & "'", cn)
'Ive tried SelectedItem, Item, Text, SelectedValue...
'For conversion i tried parse, tryparse, conversion...
cn.Open() 'Opens database connection
find1.Fill(dt1) <- I got the error here
cn.Close() 'Close database connect
mydatagrid.DataSource = dt1 'Show the result in datagridview
number criteria should be without quote
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number, " _
& "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _
& "WHERE Number =" & CInt(mycombobox.SelectedItem), cn)
But better always use parameters:
Dim comm = New OleDb.OleDbCommand("SELECT Product, Number, " _
& "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _
& "WHERE Number =?", cn)
comm.Parameters.AddWithValue("unusedName", mycombobox.SelectedItem)
Dim find1 As New OleDb.OleDbDataAdapter(comm)
In your WHERE clause have you tried to remove the quotes ? They are not required if you are looking for a number.
First, I must mention that you really ought to be using parameters. You should not concatenate the values directly into the SQL command string like that. Your SQL command string should simply contain parameter name placeholders for those values and then you should specify the values for those parameters separately.
However, if you are going to concatenate the value with the command like that, the command is a string, not an integer. It makes little sense to use CInt to convert the item to an integer just before concatenating it with a string (which requires first converting it from the integer into a string). It would make more sense to simply call ToString to convert it to a string, instead of CInt. Also, if the Number column in your database is typed as a number, rather than as text, then you should not be surrounding the value with quotes.
I recommend trying this:
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number," _
& " Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE" _
& " WHERE Number =" & mycombobox.SelectedItem.ToString(), cn)
Although, recommend is to strong a word, since I would never recommend doing it that way in the first place. Use parameterized queries!
I'm trying to import rows from one db to another, basically it something to do with this SQL:
SELECT * INTO [MSAccess;DATABASE=C:\MainDB.mdb;].[Header] FROM [Header] WHERE ID=9
As it returns this error: Could not find installable ISAM.
Any ideas? To help explain I've added my code:
Dim sSQL As String
Dim iCertMainNo As Integer
Dim cnLocal As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & App_Path() & "LocalDB.mdb;")
Dim cnMain As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & My.Settings.MainDB & ";")
cnLocal.Open()
cnMain.Open()
Dim cmd As New System.Data.OleDb.OleDbCommand("SELECT * INTO [MSAccess;DATABASE=" & My.Settings.MainDB & ";].[tblCertHeader] FROM tblCertHeader WHERE ID = " & iCertNo, cnLocal)
cmd.ExecuteNonQuery()
cnMain.Close()
cnLocal.Close()
I'm thinking it's either do it the way listed above. Or to open two connections get one row from the local and then insert it into cnMain - but again not sure how to do this without listing all the fields... Can I just simply insert the row ?
it appears you are running from one MS Access database to another, so the connect string is much simpler:
SELECT * INTO [;DATABASE=C:\MainDB.mdb;].[Header] FROM [Header] WHERE ID=9
BTW It may not be possible to update a database in C:\, if that is a real path.
EDIT I tested with this:
''Dim sSQL As String
''Dim iCertMainNo As Integer
Dim cnLocal As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Docs\dbFrom.mdb;")
''Dim cnMain As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & My.Settings.MainDB & ";")
cnLocal.Open()
''cnMain.Open()
Dim cmd As New System.Data.OleDb.OleDbCommand("SELECT * INTO [;DATABASE=C:\Docs\DBTo.mdb;].[Header] FROM Header WHERE ID = 2", cnLocal)
cmd.ExecuteNonQuery()
''cnMain.Close()
cnLocal.Close()
And it worked fine for me. I commented out iCertMainNo because you did not use it. Your string included only iCertNo, for which i used the actual value for test purposes. I did not see any reason for two connections.
I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.