The problem is conversion from string to type date is not valid - vb.net
Option Explicit On
Imports System.Data.OleDb
Public Class Form1
Dim objCon As New OleDbConnection
Dim strSQL As String
Dim strConnect As String = "Provider= Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Abry\Documents\Bilik.accdb"
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Private Sub TempahButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TempahButton.Click
Dim startDate As String = DateTimePicker1.Value.ToString("dd/MM/yyyy")
Dim str As String
startDate = DateTimePicker1.Value
objCon.ConnectionString = strConnect
objCon.Open()
str = "Insert into bilik(Bilik, Tujuan, [Masa Masuk], [Masa Keluar]) values(?, ?, ?, ?)"
str = "Insert into bilik(Tarikh) values(startDate = DateTimePicker1.Value.ToShortDateString)"
Dim cmd As OleDbCommand = New OleDbCommand(str, objCon)
cmd.Parameters.Add(New OleDbParameter("Bilik", CType(BilikComboBox.SelectedIndex, String)))
cmd.Parameters.Add(New OleDbParameter("Tujuan", CType(TujuanTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Tarikh", CType(DateTimePicker1.Value, Date)))
cmd.Parameters.Add(New OleDbParameter("Masa Masuk", CType(MasaMasukMaskedTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Masa Keluar", CType(MasaKeluarMaskedTextBox.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
objCon.Close()
TujuanTextBox.Clear()
BilikComboBox.Text = ""
DateTimePicker1.Value = ""
MasaMasukMaskedTextBox.Clear()
MasaKeluarMaskedTextBox.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Tarikh is date declare
Conversion from string to type date is not valid
The issue is, apparently, here:
DateTimePicker1.Value = ""
That means that everything else you posted is irrelevant. The issue is, as the error message clearly states, it is not valid to assign an empty String to a property that is type Date.
The Value property of a DateTimePicker is type Date and so you must assign a Date value to it. There's no such thing as an empty Date so you must either assign a default date, e.g. today's date:
DateTimePicker1.Value = Date.Today
or you need to use the functionality built into the DateTimePicker control to indicate that no date is selected. If you want to know how a DateTimePicker control works, read the class documentation.
Related
Insert string into different tables based on combobox selection
1st off, my apologies if this question has been asked. I have looked but haven't found an exact answer to the problem I'm facing. Secondly, I must stress that, I am not a developer, I'm an engineer and only writing sowftware as a needs must situation. I have a form which passes data to an access db (This works). However I need to update it so that it will pass the information to different tables within the same db based upon a selection in a combobox. For instance if combobox selection = X then insert into tableX, if combobox = Y then insert into tableY. Any and all help is appreciated. I've tried using If statements in order to select the appropriate table, but this doesn't work. Imports System.Data.OleDb Public Class Form1 Public ds As New DataSet Dim provider As String Dim dataFile As String Dim connString As String Dim myConnection As OleDbConnection = New OleDbConnection Dim rs As New resizer Dim cmd As OleDbCommand Private con As Object Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click provider = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" dataFile = "R:\Quality\NCR-Access_Database\NCRdb1.mdb" connString = provider & dataFile myConnection.ConnectionString = connString myConnection.Open() Dim str As String str = "" If ComboBox2.SelectedText = "Assembly" Then str = "Insert into [ASSEMBLYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Grinding" Then str = "Insert into [GRINDINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Milling" Then str = "Insert into [MILLINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Mill-Turn" Then str = "Insert into [MILL-TURNtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Turning" Then str = "Insert into [TURNINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Supplier" Then str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Subcon" Then str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ElseIf ComboBox2.SelectedText = "Quality" Then str = "Insert into [QUALITYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" End If cmd = New OleDbCommand(str, myConnection) cmd.Parameters.Add(New OleDbParameter("NCR-No", TextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("Week-No", TextBox3.Text)) cmd.Parameters.Add(New OleDbParameter("Part-No", TextBox4.Text)) cmd.Parameters.Add(New OleDbParameter("Drawing_Rev", TextBox5.Text)) cmd.Parameters.Add(New OleDbParameter("Description", TextBox6.Text)) cmd.Parameters.Add(New OleDbParameter("W/O-No", TextBox7.Text)) cmd.Parameters.Add(New OleDbParameter("Operator-No", TextBox8.Text)) cmd.Parameters.Add(New OleDbParameter("Operation-No", TextBox9.Text)) cmd.Parameters.Add(New OleDbParameter("Machine-No", TextBox10.Text)) cmd.Parameters.Add(New OleDbParameter("Section", ComboBox2.Text)) cmd.Parameters.Add(New OleDbParameter("Batch-Qty", TextBox12.Text)) cmd.Parameters.Add(New OleDbParameter("Reject_Qty", TextBox13.Text)) cmd.Parameters.Add(New OleDbParameter("Disposition", TextBox14.Text)) cmd.Parameters.Add(New OleDbParameter("Mat-Cost", TextBox15.Text)) cmd.Parameters.Add(New OleDbParameter("Standard-Cost", TextBox16.Text)) cmd.Parameters.Add(New OleDbParameter("Defect-Description", RichTextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("Fault-Code", TextBox17.Text)) cmd.Parameters.Add(New OleDbParameter("Dept", TextBox18.Text)) cmd.Parameters.Add(New OleDbParameter("Root-Cause", RichTextBox2.Text)) cmd.Parameters.Add(New OleDbParameter("NCR-Pinksheet", ComboBox1.Text)) cmd.Parameters.Add(New OleDbParameter("Permanent-Action", RichTextBox3.Text)) Try cmd.ExecuteNonQuery() cmd.Dispose() myConnection.Close() TextBox1.Clear() TextBox4.Clear() TextBox5.Clear() TextBox3.Clear() TextBox6.Clear() TextBox7.Clear() TextBox8.Clear() TextBox9.Clear() TextBox10.Clear() ComboBox2.ResetText() TextBox12.Clear() TextBox13.Clear() TextBox14.Clear() TextBox15.Clear() TextBox16.Clear() RichTextBox1.Clear() TextBox17.Clear() TextBox18.Clear() RichTextBox2.Clear() ComboBox1.ResetText() RichTextBox3.Clear() Catch ex As Exception MsgBox(ex.Message) End Try End Sub End Class When submitting I get a dialog that states "Command text was not set for the command object". If i submit again, then I get an exception unhandled event in VS --- "System.InvalidOperationException: 'Not allowed to change the 'ConnectionString' property. The connection's current state is open.'"
use INSERT INTO syntax INSERT INTO table-name (column-names) VALUES (values) SQL INSERT INTO with SELECT like this INSERT INTO Customer (FirstName, LastName, City, Country, Phone) SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1), SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100), City, Country, Phone FROM Supplier WHERE CompanyName = 'casterx.co'
if the input value is in between two values then display the result
I have a SQL table with three columns "From","To" and "Equivalent Value". Each value is shown below: From To Equivalent Value 1,001.00 2,000.00 200.00 2,001.00 3,000.00 300.00 Now if the user enters the value "1,200.00" in textbox1 it will display the result value to textbox2 which is "200.00" because that is the corresponding value of between "From" and "To. Another condition, if the user enters the value "2,500.00" in textbox1 it will display the value "300.00". So far, I have tried this code but no luck: Dim conn As SqlConnection = SQLConn() Dim da As New SqlDataAdapter Dim dt As New DataTable conn.Open() Dim cmd As New SqlCommand("", conn) Dim result As String cmd.CommandText = "SELECT [Equivalent Value] FROM tblSSS" result = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar) da.SelectCommand = cmd dt.Clear() da.Fill(dt) If result <> "" Then If TextBox1.Text >= dt.Rows(0)(1).ToString() And TextBox1.Text <= dt.Rows(0)(2).ToString() Then TextBox2.Text = dt.Rows(0)(3).ToString() End If End If
If I have got this right I think there are a couple of things I would change which may help you: Use Using. This will dispose of the SQL objects once finished with. Use SqlParameters. This will help with filtering your data. Remove the use of SqlDataAdapter. In this case I don't feel it's needed. The use of IIf. I will be using If which has replaced IIf. With these in mind I would look at something like this: Dim fromValue As Decimal = 0D Dim toValue As Decimal = 0D If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then Dim dt As New DataTable Using conn As SqlConnection = SQLConn, cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn) cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue}) cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue}) conn.Open() dt.Load(cmd.ExecuteReader) End Using If dt.Rows.Count = 1 Then TextBox2.Text = If(IsDBNull(dt.Rows(0).Item("Equivalent Value")), "0", dt.Rows(0).Item("Equivalent Value").ToString) End If End If Note the use of Decimal.TryParse: Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed. This is an assumption that the From and To fields in your database are Decimal. Now to explain the difference between IIf and If. IIf executes each portion of the statement even if it's true whilst If executes only one portion. I won't go into detail as many others on here have done that already. Have a look at this answer. As per Andrew Morton's comment and more in line with what the OP attempted here is a solution that uses ExecuteScaler. ExecuteScaler executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. With this in mind: 'I reset the value of TextBox2.Text. You may not want to. TextBox2.Text = "" Dim fromValue As Decimal = 0D Dim toValue As Decimal = 0D If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then Using conn As SqlConnection = SQLConn, cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn) cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue}) cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue}) conn.Open() Try TextBox2.Text = cmd.ExecuteScalar().ToString() Catch ex As Exception End Try End Using End If I have used the example on the ExecuteScaler MSDN documentation. You might want to look into handling the exception on the Try Catch a little better and not letting it go to waste. You may want to place this code on the TextBox1.Leave method or maybe on a Button.Click method. That's totally up to you. There may a few changes you may need to make however I think this will give you a few ideas on how to move ahead with your code.
Hope it Helps... Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "SELECT [Equivalent Value] FROM tblSSS WHERE [FROM]<=" & Val(TextBox1.Text) & " AND [TO]>= " & Val(TextBox1.Text) cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try
How do you stop and reset a form before it submits data to a database
I am making a login page and I have done the registration form, however, I need to validate the username. I have done the validating part, however, I can't seem to get it to not submit the data and reset the username box. This is the code Imports System.Data.OleDb Public Class Register Dim provider As String Dim dataFile As String Dim connString As String Dim myConnection As OleDbConnection = New OleDbConnection Private Sub rB_Click(sender As Object, e As EventArgs) Handles rB.Click provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" dataFile = "C:\Users\Harry\Documents\Visual Studio 2015/users.accdb" connString = provider & dataFile myConnection.ConnectionString = connString myConnection.Open() Dim usf As OleDbCommand = New OleDbCommand("SELECT * FROM [users] WHERE [username] = '" & uT.Text, myConnection) Dim userFound As Boolean = True If userFound = True Then MsgBox("Username already found; Please choose another") Dim frm = New Register frm.Show() Me.Close() End If Dim str As String str = "insert into users ([username], [password], [Firstname], [LastName]) values (?, ?, ?, ?)" Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection) cmd.Parameters.Add(New OleDbParameter("username", CType(uT.Text, String))) cmd.Parameters.Add(New OleDbParameter("password", CType(pT.Text, String))) cmd.Parameters.Add(New OleDbParameter("FirstName", CType(fnT.Text, String))) cmd.Parameters.Add(New OleDbParameter("LastName", CType(lnT.Text, String))) Try cmd.ExecuteNonQuery() cmd.Dispose() myConnection.Close() uT.Clear() pT.Clear() fnT.Clear() lnT.Clear() Me.Hide() Form2.Show() Catch ex As Exception MsgBox(ex.Message) End Try End Sub
First, please post your code instead of including an image as it's hard to reference back to when describing problems found. That being said. You have a boolean UserFound that you are declaring and setting to True and then immediately checking to see if it's true. Of course it's going to be true, you just set it. Also, I see nowhere in that image where you're even passing the query to get results back. (ie, executeReader, executeScalar) Typically you can query the database and then check to see if any rows were returned or use executeScalar against a single column to see if a value was returned.
No value given for one or more required parameters vb.net oledb
Public Class ViewPhoneRecords Dim con As New OleDb.OleDbConnection Dim dbProvider As String Dim dbSource As String Dim da As OleDb.OleDbDataAdapter Dim ds As New DataSet Dim sqlquery As New OleDb.OleDbCommand Dim con1 As New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb") Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click Dim sqlupdate As String ' Here we use the UPDATE Statement to update the information. To be sure we are ' updating the right record we also use the WHERE clause to be sureno information ' is added or changed in the other records sqlupdate = "UPDATE PhoneRecords SET Forename=#Forename, Surname=#Surname, Address=#Address, PhoneModel=#PhoneModel, PhoneNumber=#PhoneNumber, Postcode=#Postcode WHERE IDNum='" & IDTextBox.Text & "'" Dim cmd As New OleDbCommand(sqlupdate, con1) ' This assigns the values for our columns in the DataBase. ' To ensure the correct values are written to the correct column cmd.Parameters.Add(New OleDbParameter("#Forename", ForenameTextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("#Surname", SurnameTextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("#Address", AddressTextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("#PhoneModel", PhoneModelTextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("#PhoneNumber", PhoneNumberTextBox1.Text)) cmd.Parameters.Add(New OleDbParameter("#Postcode", PostcodeTextBox1.Text)) con1.Open() cmd.ExecuteNonQuery() MsgBox("Row(s) Inserted !! ") 'Displays message box informing the user that the database has been added to con1.Close() 'Connection closed Me.Refresh() End Sub This is supposed to update a selected record in a datagrid view. However, when I click the 'Save changes' button, an error is given; "No value given for one or more parameters." Any idea how to solve this?
Use cmd.Parameters.AddWithValue instead of cmd.Parameters.Add
Converting string to integer VB.NET
I'm having trouble finding the right format for converting my txtID and txtCatID into integers since it's in numbers in the database access. Code Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btnSave.Click Dim sqlinsert As String sqlinsert = _ "INSERT INTO Products (ProductID, Product, UnitPrice, CategoryName, CategoryID)" & _ " VALUES (#ProductID, #Product, #UnitPrice, #CategoryName, #CategoryID)" Dim cmd As New OleDb.OleDbCommand(sqlinsert, con1) cmd.Parameters.Add(New OleDbParameter("#ProductID", (txtID.Text))) cmd.Parameters.Add(New OleDbParameter("#Product", txtProd.Text)) cmd.Parameters.Add(New OleDbParameter("#UnitPrice", txtPrice.Text)) cmd.Parameters.Add(New OleDbParameter("#CategoryName",txtCategory.Text)) cmd.Parameters.Add(New OleDbParameter("#CategoryID", (txtCatID.Text))) con1.Open() cmd.ExecuteNonQuery() con1.Close() ClearTextBox(Me) RefreshDGV() Me.Close()
You can convert String to int by doing like this: For C#: int val = Int32.Parse("12"); For VB.NET: Dim val as Integer = CInt("12") Here you can find all Type Conversion Functions (Visual Basic). Here you have How to: Convert a String to a Number (C# Programming Guide).
You can convert string from a TextBox to an integer using: Dim myInt as Integer = CInt(Textbox1.Text) Otherwise, if you are asking how to ensure that an integer is appended into an SQL file or Access file using VB.NET, then that's a different question.
I solved it: Dim productID As Integer If (Integer.TryParse(txtID.Text, productID)) Then cmd.Parameters.Add(New OleDbParameter("#ProductID", productID)) Else Throw New ArgumentException("Entered ProductID is not a valid integer.") End If cmd.Parameters.Add(New OleDbParameter("#Product", txtProd.Text)) Dim price As Double If (Double.TryParse(txtPrice.Text, price)) Then cmd.Parameters.Add(New OleDbParameter("#UnitPrice", txtPrice.Text)) Else Throw New ArgumentException("Invalid.") End If cmd.Parameters.Add(New OleDbParameter("#CategoryName", txtCategory.Text)) Dim id As Integer If (Integer.TryParse(txtCatID.Text, id)) Then cmd.Parameters.Add(New OleDbParameter("#CategoryID", id)) Else Throw New ArgumentException("Entered Category ID is Invalid.") End If