I want to find a specific value from an Access database. Then manipulate this value as part of validation (weigh a user inputted value against a min and max values in the database)
I can get the data in from the database but I can't seem to fill a data table. I want to user to type in the primary key and then when the button is clicked an SQL statment uses that input to find the value then put that value into a Data Table and spit that value out on a textbox. I figure if I can get it spitting out the right value then I can put the value into a variable that I can manipulate.
I don't need to change the data in the database I just need to collect the values in order to verify user entered data. Here is the code I have so far.
Private Sub btnValidate_Click_1(sender As System.Object, e As System.EventArgs) Handles btnValidate.Click
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
dbConnect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\crabara\Desktop\Project Alpha 3\MDB.accdb;Persist Security Info=False;"
dbConnect.Open()
da = New OleDb.OleDbDataAdapter("SELECT MoldVinylWeightMin FROM PROCESS_INFO WHERE PCRNumber =" & txtPcr.Text, dbConnect)
da.Fill(ds, "MinWeight")
TextBox1.Text = ds.Tables("MinWeight").Rows(0).Item(0)
End Sub
Right now it throws the error "Data type mismatch in criteria expression." Any help would be great, I can't find much info on this.
If PRCNumber is a numeric type in the database you will not need to quote it
so: PCRNumber ='" & txtPcr.Text & "'"
becomes
PCRNumber = " & txtPcr.Text
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'm working on a project where a form will pull information from an Access database. We have techs that are assigned to various stores, and instead of listing all of the stores and assigning a tech, I was looking to have a list of techs and assigning stores. Right now, the database has 4 fields.
Gate Tech - Text Field
Expiration Date - Date Field
Doors - Yes/No checkbox
Stores - Lookup & Relationship field that can have multiple selections
My form has a text box, search button, and a rich text box. If someone puts in a store number, it searches the Lookup & Relationship field and if that store is checked then it will put the tech in the rich text box.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim text1 As String = TextBox1.Text
myConnection.Open()
Dim lstscmd As OleDbCommand = New OleDbCommand("SELECT * FROM Table1 WHERE Stores = #Stores", myConnection)
lstscmd.Parameters.AddWithValue("#Stores", CInt(text1))
dr = lstscmd.ExecuteReader
While dr.Read
RichTextBox1.AppendText(dr("Gate Tech").ToString + Environment.NewLine)
End While
myConnection.Close()
End Sub
At While dr.Read I get
Row handles must all be released before new ones can be obtained.
I would like it search the Stores field for any selected stores, and return the Gate Tech value to the rich text box.
Any help with this would be greatly appreciated.
I found where I was going wrong and the best way to solve it.
Instead of pulling the data from the table field, I created a query in access and pointed my search to that.
Dim lstscmd As OleDbCommand = New OleDbCommand("SELECT * FROM Table1 WHERE Stores = #Stores", myConnection)
lstscmd.Parameters.AddWithValue("#Stores", CInt(text1))
Replace Table1 (or your table name) with Query1 (or your query name) and it should start pulling values.
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.)
I have a ms access database connected to my vb application through the data wizard.
i want to allow the user to search the database and display their results on a datagrid.
for example user searches for 50 – 55 year Old man under 1.8 meters in height
so far i can display the total amount of people on the database with this code
Private Sub lblTotalPeople_Click(sender As System.Object, e As System.EventArgs) Handles lblTotalPeople.Click
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\AssignmentDatabase.accdb")
' Use wildcard'
Dim cmd As OleDbCommand = New OleDbCommand("Select COUNT(*) From Table1", con)
'' or Where username='" & TextBox1.Text & "'
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Table1")
DataGridView2.DataSource = myDataSet.Tables("Table1").DefaultView
End Sub
how would i search the database based on what the user searches or what would i use?
Assuming you don't already you need to learn how to use SQL.
In your code above the SQL statement is
Select COUNT(*) From Table1
You would need to replace this SQL with a search that uses a value from the user (most likely from a textbox). This text
'' or Where username='" & TextBox1.Text & "'
appears to be part way to some SQL that may work but it looks dangerous. You should also research SQL Injection as using this directly means users could access/damage your Access database.
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.