Converting string to integer VB.NET - vb.net-2010

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

Related

The problem is conversion from string to type date is not valid

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.

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'

Procedure only updates the first value

I have this SQL procedure for updating records given a #StepId value.
I got the values from a hidden field as an array and I loop them.
The problem is that the procedure only updates the first value.
The loop happen but do not update more than 1 value.
my array contains something like {1000,2000,3000,}
my parameters are
#StepId (int)
#DateCalculationRule (char)
#Result (int)
Private Sub buttonCalculateDatesClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonCalculateDates.Click
Dim mySteps As String
Dim myRule As String
Dim ok As Integer = 1
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("cnnstring").ConnectionString
Dim conn As SqlConnection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("SaveStepDeadlineRule", conn)
conn.Open()
conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
myRule = HiddRule.Value
mySteps = HiddStepIDs.Value
'Separate string by comas
Dim parts As String() = mySteps.Split(New Char() {","c})
Dim part As String
For Each part In parts
cmd.Parameters.Add(New SqlParameter("#StepId", part))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", myRule))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next
conn.Close()
End Sub
You will need to clear down your parameters each time you loop:
cmd.Parameters.Clear
This is how it would be used:
For Each part In parts
cmd.Parameters.Clear()
cmd.Parameters.Add(New SqlParameter("#StepId", part))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", myRule))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next
You could create the parameters outside the loop since they don't change and then just assign the value each time you loop:
cmd.Parameters.Add(New SqlParameter("#StepId", 0))
cmd.Parameters.Add(New SqlParameter("#DateCalculationRule", ""))
cmd.Parameters.Add(New SqlParameter("#Result", 0))
cmd.Parameters("#Result").Direction = ParameterDirection.Output
For Each part In parts
cmd.Parameters("#StepId").Value = part
cmd.Parameters("#DateCalculationRule").Value = myRule
Try
cmd.ExecuteNonQuery()
ok = IIf(IsDBNull(cmd.Parameters("#Result").Value), 1, cmd.Parameters("#Result").Value)
RadGrid1.Rebind()
Catch ex As Exception
ok = 1
End Try
Next

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

OleDB INSERT STATEMENT Error

I'm working on a project where I'm going to add records in database. My big problem is the "INSERT INTO" statement, after searching and debugging still no success. This is a part of the code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim sqlinsert As String = "INSERT INTO tblList([Access Number],[Book Title],Subject,Author,Edition,Page,Publisher,Years,Copy)" & "VALUES(#Access Number,#Book Title,#Subject,#Author,#Edition,#Page,#Publisher,#Years,#Copy)"
Dim cmd As New OleDbCommand(sqlinsert, con)
cmd.Parameters.Add(New OleDbParameter("#Access Number", txtan.Text))
cmd.Parameters.Add(New OleDbParameter("#Book Title", txtbt.Text))
cmd.Parameters.Add(New OleDbParameter("#Subject", txtsub.Text))
cmd.Parameters.Add(New OleDbParameter("#Author", txtau.Text))
cmd.Parameters.Add(New OleDbParameter("#Edition", txted.Text))
cmd.Parameters.Add(New OleDbParameter("#Page", txtpg.Text))
cmd.Parameters.Add(New OleDbParameter("#Publisher", txtpub.Text))
cmd.Parameters.Add(New OleDbParameter("#Years", txtyr.Text))
cmd.Parameters.Add(New OleDbParameter("#Copy", txtco.Text))
cmd.ExecuteNonQuery()
MsgBox("One Record Added")
Refreshlist()
clear()
End Sub
Help me please? I am so confused.
Thanks a lot.
(A am using ms access and vb.net in visual studio 2008)
Upon digging on some of my old programs, this is how I pass parameters to ms access:
Dim sqlinsert As String= "INSERT INTO tblList([Access Number],[Book Title],Subject,Author,Edition,Page,Publisher,Years,Copy)" & _
"VALUES(?,?,?,?,?,?,?,?,?)"
Dim cmd as new OleDbCommand(sqlinsert, con)
cmd.Connection.Open
With cmd.Parameters
.AddWithValue("access_number", txtan.text)
.AddWithValue("book_title", txtbt.text)
.AddWithValue("subject", txtsub.text)
.AddWithValue("author", txtau.text)
.AddWithValue("edition", txted.text)
.AddWithValue("page", txtpg.text)
.AddWithValue("publisher", txtpub.text)
.AddWithValue("years", txtyr.text)
.AddWithValue("copy", txtco.text)
End With
cmd.ExecuteNonQuery()
Also, I'd be wary of using spaces on your column names,
specifically on Access Number and Book Title
P.S.
.AddWithValue("a", b)
a = this can be anything but as a personal rule of mine, i tend to name it based on the column name
b = the value you want to pass
Try change the name of these parameters from
"#Access Number" to: "#Access_Number"
"#Book Title" to: "#Book_Title"