How can I convert varchar to numeric in visual studio? - visual-studio

Please help me,Im trying to do a fixed asset program in visual basic studio using sql server, Im stack in this.
I checked if my sql table data types match with the visual studio data types.
Public Class Equipos_de_Computacion
Dim sql As String = ""
Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
If (Me.txtCodigoInterno.Text = "") Then
MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
Me.txtCodigoInterno.Select()
Else
Dim CodigoInterno As Integer
Dim NumerodeSerie As Integer
Dim NumerodeFactura As Integer
Dim FechadeCompra As Date
Dim Precio As Decimal
Dim Acargode As String = ""
Dim Estado As String = ""
Dim Depreciacion As Decimal
Dim Caracteristicas As String = ""
CodigoInterno = Me.txtCodigoInterno.Text
NumerodeSerie = Me.txtNumerodeSerie.Text
NumerodeFactura = Me.txtNumerodeFactura.Text
FechadeCompra = Me.DateTimePicker1.MinDate
Precio = CDec(txtPrecio.Text)
Acargode = Me.txtACargode.Text
Estado = Me.txtEstado.Text
Depreciacion = CDec(txtDepreciacion.Text)
Caracteristicas = Me.txtCaracteristicas.Text
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion) "
sql += "Values('" & CodigoInterno & "','" & NumerodeSerie & "','" & NumerodeFactura & "','" & FechadeCompra & "','" & CDec(Precio) & "','" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & CDec(Depreciacion) & ")"
MsgBox(sql)
cmd.CommandText = sql
Try
cmd.ExecuteNonQuery()
MsgBox("Registro insertado correctamente")
Catch ex As Exception
If ex.ToString.Contains("duplicate") Then
MsgBox("El registro ya existe en la base de datos")
Else
MsgBox(ex.ToString)
End If
End Try
End If
End Sub
it sends me converting varchar to numeric error.

Iam only able to insert integer numbers.With Cint
`Imports System.Data.SqlClient
Public Class Equipos_de_Computacion
Dim sql As String = ""
Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
If (Me.txtCodigoInterno.Text = "") Then
MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
Me.txtCodigoInterno.Select()
Else
Dim CodigoInterno As Integer
Dim NumerodeSerie As Integer
Dim NumerodeFactura As Integer
Dim FechadeCompra As Date
Dim Precio As Decimal
Dim Acargode As String = ""
Dim Estado As String = ""
Dim Depreciacion As Decimal
Dim Caracteristicas As String = ""
CodigoInterno = CInt(Me.txtCodigoInterno.Text)
NumerodeSerie = CInt(Me.txtNumerodeSerie.Text)
NumerodeFactura = CInt(Me.txtNumerodeFactura.Text)
FechadeCompra = CDate(Me.DateTimePicker1.Text)
Precio = Me.nudPrecio.Value
Acargode = Me.txtACargode.Text
Estado = Me.txtEstado.Text
Depreciacion = Me.NudDepreciacion.Value
Caracteristicas = Me.txtCaracteristicas.Text
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion)"
sql += "Values( '" & CodigoInterno & "' , '" & NumerodeSerie & "' , '" & NumerodeFactura & "' ,'" & FechadeCompra & "', '" & Precio & "' ,'" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & Depreciacion & "' )"
MsgBox(sql)
cmd.CommandText = sql
Try
cmd.ExecuteNonQuery()
MsgBox("Registro insertado correctamente")
Catch ex As Exception
If ex.ToString.Contains("duplicate") Then
MsgBox("El registro ya existe en la base de datos")
Else
MsgBox(ex.ToString)
End If
End Try
End If
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvEquiposdeComputacion.CellContentClick
End Sub
Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click
Dim DS As New DataSet
Dim DA As New SqlDataAdapter("Select * from [Equipos de Computacion]", conn)
DA.Fill(DS)
dgvEquiposdeComputacion.DataSource = DS.Tables(0)
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
End Sub
Private Sub BtnTotalDepreciacion_Click(sender As Object, e As EventArgs) Handles btnTotalDepreciacion.Click
NudDepreciacion.Value = CDec(FormatNumber(nudPrecio.Value * 0.25, 2))
End Sub
Private Sub TxtPrecio_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub txtPrecio_KeyPress(sender As Object, e As KeyPressEventArgs) Handles nudPrecio.KeyPress
nudPrecio.DecimalPlaces = 2
End Sub
Private Sub txtPrecio_LostFocus(sender As Object, e As EventArgs)
Dim VarMonedaDolares As Double
VarMonedaDolares = nudPrecio.Value
nudPrecio.Value = CDec(FormatCurrency(VarMonedaDolares, 2))
End Sub
End Class`

Related

Different output from same coding vb.net

im new here and want asking one question.
i have form with button that when clicked will fill database, but when im using keydown event the result is different.
here is the result, red box from click button and the green one from keydown event.
enter image description here
here is my code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Masukan kode dan nama sub kelompok terlebih dahulu")
Else
For baris As Integer = 0 To DataGridView1.Rows.Count - 2
Dim inputsub As String = "insert into mastersubkelompok values('" & DataGridView1.Rows(baris).Cells(0).Value & "','" & DataGridView1.Rows(baris).Cells(1).Value & "','" & DataGridView1.Rows(baris).Cells(2).Value & "','" & TextBox1.Text & "')"
CMD = New OleDbCommand(inputsub, CONN)
CMD.ExecuteNonQuery()
MsgBox("Data berhasil di input")
Call kondisiawal()
Next
End If
End Sub
Private Sub SubKelompok_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown, DataGridView1.KeyDown
If e.KeyCode = Keys.F2 Then
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Masukan kode dan nama sub kelompok terlebih dahulu")
Else
For baris As Integer = 0 To DataGridView1.Rows.Count - 2
Dim inputsub As String = "insert into mastersubkelompok values('" & DataGridView1.Rows(baris).Cells(0).Value & "','" & DataGridView1.Rows(baris).Cells(1).Value & "','" & DataGridView1.Rows(baris).Cells(2).Value & "','" & TextBox1.Text & "')"
CMD = New OleDbCommand(inputsub, CONN)
CMD.ExecuteNonQuery()
MsgBox("Data berhasil di input")
Call kondisiawal()
Next
End If
End If
End Sub

Argument name not found for PL/SQL procedure, only in IIS7 (not IIS6)

I have a stored procedure in oracle getspname which I will receive 2 input parameters (varchar2 and number) and one output param of cursor type.
The application that is executing this stored procedure is a bit old, it is using VB6 in IIS6 to connect to this SP in ORACLE and I am migrating it to IIS7.
Provider=MSDAORA.1;Data Source=XXXXXXXX;User ID=XXXXXXXXX;Password=XXXXXX
and SQL is:
{call schema.Pkg_name.getspname(?,?,{resultset 0, io_cursor})}
Params: 11111111;0
IN IIS6 has no problem executing the procedure and returning the cursor data,
in IIS7 if not, it sent input parameters, this also works, but I need to send it these fields to comply with the applied business logic.
This solution was also implemented but the error is replicated in SP that has only input or output parameters of type varchar2 stackoverflow.com/a/50643323/5904375
VB6:
Public Function execProcedure( _
ByVal sConnString As String, _
ByVal sSQL As String, _
ByRef oRs As Variant, _
ByVal sParameters As Variant, _
ByRef vntRespuesta As Variant, _
Optional Encrypt As Boolean _
) As Integer
Dim Params, i
Dim RsCmd
Dim oRecordSet
Dim RspMsg As Variant
Dim RspMsg1 As Variant
Dim RspMsg2 As Variant
Dim oConec
Dim BeforeConn As Boolean
Dim auxErr As Integer
Dim auxValue As Variant
Dim StringReg As Variant
Dim oEncrypt
Dim bEncrypt As Boolean
On Error GoTo Error_handler
'** Se verifica encriptacion del string de conexion
bEncrypt = False
If Not IsMissing(Encrypt) Then
If Encrypt Then bEncrypt = True
End If
If bEncrypt Then
Set oEncrypt = CreateObject("NR_DBconn.Encrypt")
StringReg = oEncrypt.EncriptarChrTran("azv", sConnString, 2)
Set oEncrypt = Nothing
Else
StringReg = sConnString
End If
BeforeConn = True
Set ctxObject = GetObjectContext
strNombreObjeto = "ADODB.Command"
Set RsCmd = ctxObject.CreateInstance("ADODB.Command")
'Set RsCmd = CreateObject("ADODB.Command")
strNombreObjeto = "ADODB.Recordset"
Set oRecordSet = ctxObject.CreateInstance("ADODB.Recordset")
'Set oRecordSet = CreateObject("ADODB.Recordset")
strNombreObjeto = "ADODB.Connection"
Set oConec = ctxObject.CreateInstance("ADODB.Connection")
'Set oConec = CreateObject("ADODB.Connection")
'*
'* Verifica si el sSQL es válido
'*
If sSQL = "" Or Len(sSQL) = 0 Then
ctxObject.SetAbort
'La transaccion finaliza con error
Err.Raise INSTRUCCION_INVALID, "Verificar sSQL"
End If
'*
'* Se verifica string de conexión
'*
If (StringReg = "") Then
ctxObject.SetAbort
'La transaccion finaliza con error
Err.Raise INSTRUCCION_INVALID, "Verificar string de Conexion"
End If
BeforeConn = False
oConec.Open StringReg
With RsCmd
.ActiveConnection = oConec
.CommandText = sSQL
.CommandType = adCmdText ' adCmdStoredProc 'adCmdText
If Len(sParameters) <> 0 Then
Params = Split(sParameters, ";")
For i = 0 To UBound(Params)
.Parameters(i).Direction = adParamInput
.Parameters(i).Value = Params(i)
Next i
End If
End With
oRecordSet.CursorLocation = adUseClient
oRecordSet.CursorType = adOpenStatic
oRecordSet.LockType = eltBatchOptimistic
Set oRecordSet = RsCmd.Execute()
'*
'* Verifica el resultado
'*
auxErr = -1
If oRecordSet.State = 1 Then
If oRecordSet.EOF Or oRecordSet.BOF Or oRecordSet Is Nothing Then
RspMsg1 = "0"
RspMsg2 = "No se obtuvo recordset de vntRespuesta - warning"
RspMsg = "[" & RspMsg1 & "]: " & RspMsg2
auxErr = 0
Set oRs = Nothing
Else
RspMsg1 = "0"
RspMsg2 = ""
RspMsg = "" '"[" & RspMsg1 & "]: " & RspMsg2
'------traspasa el recordsetresult a recordset desconectado
Dim Rsx
Dim j
Dim NumFields
Set Rsx = New ADODB.Recordset
NumFields = oRecordSet.Fields.Count - 1
With Rsx
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = eltBatchOptimistic
Set .ActiveConnection = Nothing
For i = 0 To NumFields
With .Fields
.Append oRecordSet.Fields(i).Name, adBSTR
End With
Next i
.Open
Do While Not oRecordSet.EOF
.AddNew
For j = 0 To NumFields
auxValue = oRecordSet.Fields(j)
.Fields(j) = CheckNull(auxValue)
Next j
oRecordSet.MoveNext
Loop
.MoveFirst
End With
'-------------
Set oRs = Rsx
'Set oRecordSet.ActiveConnection = Nothing
Set oRecordSet = Nothing
Set Rsx = Nothing
auxErr = 1
End If
Else
RspMsg1 = "2"
RspMsg2 = "No se obtuvo recordset de vntRespuesta - operacion no necesita"
RspMsg = "[" & RspMsg1 & "]: " & RspMsg2
auxErr = 2
Set oRs = Nothing
End If
vntRespuesta = RspMsg
Set RsCmd = Nothing
oConec.Close
Set oConec = Nothing
' If IsObject(oRs) Then
' execProcedure = oRs.RecordCount
' Else
execProcedure = auxErr
' End If
'*
'* La transacción finaliza exitosamente
ctxObject.SetComplete
Exit Function
Error_handler:
execProcedure = -1
RspMsg = ErrorMessage("SQLserver.execProcedure.", Err.Number, Err.Source, Err.Description, sSQL)
'*
'* Fin de la función, ha ocurrido un Error Fatal
'*
On Error Resume Next
If Not BeforeConn Then
If (oConec.State = adStateOpen) Then
oConec.Close
End If
End If
Set oConec = Nothing
vntRespuesta = RspMsg
'*
'* La transacción finaliza con error
'*
ctxObject.SetAbort
End Function
Function Error VB6:
Private Function ErrorMessage(ErrPath, ErrCod, ErrSource, ErrDescription, sSQL)
Dim RspMsg1
Dim RspMsg2
Dim strPathError
strPathError = "[" & ErrPath & "." & Err.Source & "] "
Select Case (ErrCod)
Case INSTRUCCION_INVALID
RspMsg1 = INSTRUCCION_INVALID
RspMsg2 = strPathError & " El string 'sSQL' esta mal formado." & _
"Verifique que el String 'sSQL' esté de acuerdo al formato SQL"
Case STRING_CONNECTION
RspMsg1 = STRING_CONNECTION
RspMsg2 = strPathError & "No existe string de conexion para esta Aplicacion "
Case NOT_REC_RETURN
RspMsg1 = NOT_REC_RETURN
RspMsg2 = strPathError & "No se retornaron registros." & _
"Intente de nuevo o con otros valores en el 'sSQL'. Este error puede deberse a una falla en la conexion con la Base de Datos. (" & sSQL & ")"
Case NOT_REC_FOUND
RspMsg1 = NOT_REC_FOUND
RspMsg2 = strPathError & "No se encontro registros." & _
"Intente con otros valores en la 'sSQL'. (" & sSQL & ")"
Case 429:
RspMsg1 = "-1"
RspMsg2 = strPathError & " No se puede crear el componente: '" & strNombreObjeto & _
"Verifique que el componente esté instalado correctamente."
'Error manipulado. En parametros de la base de datos.
Case -2147217887
RspMsg1 = "-1"
RspMsg2 = strPathError & "Error al insertar campo." & _
"Verifique el largo del valor del campo no exceda al maximo permitido en la definicion de la TABLA de la Base de Datos."
Case Else 'Cualquier otro tipo de Error
RspMsg1 = "-1"
RspMsg2 = strPathError & ErrDescription
End Select
ErrorMessage = "[" & RspMsg1 & "]: " & RspMsg2
End Function
This SP was also independently tested to rule out any problem, it works correctly
SP ORACLE:
PROCEDURE getspname (value IN varchar2 ,value2 IN number , io_cursor IN OUT t_cursor)
AS
BEGIN
........
END;
END getspname;
I solved this on Friday 08/17/2020 at 3 AM,
I decided to make a call directly to the oracle SP from the ASP using provider (OraOLEDB.Oracle) and thus replicate the behavior, this was giving an error of "Run-time error 3001 Arguments Are Of The Wrong Type… when setting ADODB.Command object members"
The ASP code:
Name file: test.asp
<%# Language=VBScript %>
<%Response.Buffer = false%>
<%Response.Expires = 0%>
<%
Dim strConnect
strConnect = "Provider=OraOLEDB.Oracle;Data Source=XXXXXXXX;User ID=XXXXXXXXX;Password=XXXXXX"
Dim cn, rs, cmd, param
set cn = Server.CreateObject( "ADODB.Connection" )
cn.Open Cstr(strConnect)
set cmd = server.CreateObject ("ADODB.Command")
with cmd
set .ActiveConnection = cn
.NamedParameters = True
.CommandText = "{call schema.Pkg_name.getspname({resultset 0, io_cursor})}"
.CommandType = 1
end with
set rs = server.CreateObject ( "ADODB.Recordset" )
set rs = cmd.execute
Set rs = cmd.Execute
Do Until rs.EOF
for each x in rs.fields
response.write(x.name)
response.write("=")
response.write(x.value)
response.write(", ")
next
response.write("<br />")
rs.MoveNext
Loop
rs.Close
%>
<%
Dim strConnect_cn
strConnect_cn = "Provider=OraOLEDB.Oracle;Data Source=XXXXXXXX;User ID=XXXXXXXXX;Password=XXXXXX"
Dim cn_cn, rs_cn, cmd_cn , param1, param2
set cn_cn = Server.CreateObject( "ADODB.Connection" )
cn_cn.Open Cstr(strConnect_cn)
set cmd_cn = server.CreateObject ("ADODB.Command")
with cmd_cn
set .ActiveConnection = cn_cn
.CommandText = "{call schema.Pkg_name.getspname(?,?,{resultset 0, io_cursor})}"
.CommandType = 1
end with
cmd_cn.parameters.append(cmd_cn.createParameter("", adVariant, adParamInput, , "11111111"))
cmd_cn.parameters.append(cmd_cn.createParameter("", adVariant, adParamInput, , "0"))
set rs_cn = server.CreateObject ( "ADODB.Recordset" )
set rs_cn = cmd_cn.execute
Set rs_cn = cmd_cn.Execute
Do Until rs_cn.EOF
for each x in rs_cn.fields
response.write(x.name)
response.write("=")
response.write(x.value)
response.write(", ")
next
response.write("<br />")
rs_cn.MoveNext
Loop
rs_cn.Close
%>
<html>
<head>
<title> Links </title>
</head>
<body>
<p>test.asp</p>
</body>
</html>
This code throws me the following problem with input parameters, where the arguments were of the wrong type.
"Run-time error 3001 ‘Arguments Are Of The Wrong Type, Are Out Of The
Acceptable Range, or are in conflict with one another’ upon invocation
of"
And according to the documentation that I found this is fine
http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/asp/met_comm_createparameter.asp.html
https://welookups.com/asp/ado_datatypes.html
https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/datatypeenum?view=sql-server-ver15
After much searching in forums on the Internet I found that the following article:
http://keencod.in/?p=23
This explains:
...that error is fired because of late binding of library references,
so VB simply did not know of adCmdStoredProc and other constants. That
meant that this error has nothing to do with ADODB or Ole or SP...
Therefore, you only had to declare these values at the beginning as constants, just as explained in the article.
So at the beginning of my ASP (test.asp) code add:
Const adVarChar = 200
Const adParamInput = &H1
Const adParamOutput = &H2
Const adCmdStoredProc = &H4
Const adVariant = 12
And magic, it worked!!
Then I modified my VB6 code, which was the one I had to use to comply with the business logic of the applications that were being migrated.
At the beginning of the file add:
Const adVarChar As Long = 200
Const adParamInput As Long = &H1
Const adParamOutput As Long = &H2
Const adCmdStoredProc As Long = &H4
Const adCmdText As Long = 1
Const adUseClient As Long = 3
Const adOpenStatic As Long = 3
Const adVariant As Long = 12
And then change my VB6 code like this:
With RsCmd
.ActiveConnection = oConec
.CommandText = sSQL
.CommandType = adCmdText ' adCmdStoredProc 'adCmdText
If Len(sParameters) <> 0 Then
.NamedParameters = True
Params = Split(sParameters, ";")
For i = 0 To UBound(Params)
.Parameters.Append (.CreateParameter("", adVariant, adParamInput, , Params(i)))
Next i
End If
End With
Using provider: MSDAORA.1
And with this the problem was solved!!
This is my story, thank you very much!!
End.

Need help fixing Exception Unhandled

I am getting the following error:
System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string.
Parameter name: length'
(Look for Bold Italic on code *** that's where it is taking me to fix that)
Not sure what the problem is. Here is the whole code:
Imports GroceryApp.GroceryItem
Imports System.IO
Public Class GroceryItemForm
Private strFileName As String = String.Empty
Private Sub btnAddToBasket_Click(sender As Object, e As EventArgs) Handles btnAddToBasket.Click, AddToolStripMenuItem.Click
Dim gi As GroceryItem
Dim price As Double
' Validate that brand name is entered
If txtBrandName.Text = "" Then
MsgBox("Please input an Brand Name", , "Value Required")
txtBrandName.Focus()
Exit Sub
End If
' Validate that price is entered
If Not Double.TryParse(numPrice.Text, price) Then
MsgBox("Please input an Price", , "Value Required")
numPrice.Focus()
Exit Sub
End If
' Validate that Aisle is selected
If cboAisle.Text = "" Then
MsgBox("Please select an Aisle", , "Value Required")
cboAisle.Focus()
Exit Sub
End If
***txtScanNumber.Text = txtBrandName.Text.Substring(0, 3) & "1019"***
gi = New GroceryItem(txtScanNumber.Text, txtBrandName.Text, price)
gi.Type = [Enum].Parse(GetType(Aisle), cboAisle.Text)
gi.Description = txtDescription.Text
basket.Add(gi)
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub ViewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewToolStripMenuItem.Click
'Dim result As String = ""
'Dim i As Integer = 1
'For Each gi As GroceryItem In basket
'result = result & "Item " & i & vbNewLine & "Aisle: " & gi.Type.ToString & vbNewLine & "Scan Number: " & gi.ScanNumber & vbNewLine & "Brand Name: " & gi.BrandName & vbNewLine & vbNewLine
'i = i + 1
'Next
'MsgBox(result, , "Basket Details")
Dim oForm As BasketDisplayForm
oForm = New BasketDisplayForm()
oForm.Show()
oForm = Nothing
End Sub
Private Sub GroceryItemForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oForm As LoginForm
oForm = New LoginForm()
oForm.Show()
oForm = Nothing
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim rowLine As String = ""
'If strFileName = String.Empty Then
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFileName = SaveFileDialog1.FileName
Dim fsStream As New FileStream(strFileName, FileMode.Append, FileAccess.Write)
Dim sw As New StreamWriter(fsStream)
Dim sb As New System.Text.StringBuilder
For Each Item As GroceryItem In basket
sb.AppendLine(String.Concat(Item.ScanNumber, ",", Item.Type.ToString, ",", Item.BrandName, ",", Item.Description, ",", Item.Price))
'rowLine = rowLine + Item.ScanNumber + "," + Item.Type.ToString + "," + Item.BrandName + "," + Item.Description + "," + Item.Price.ToString
Next
'IO.File.WriteAllText(strFileName, sb.ToString)
'rowLine = rowLine.Remove(rowLine.Length - 1, 1)
sw.WriteLine(sb)
sw.Flush()
MsgBox("Data Saved Successfully")
sw.Close()
basket.Clear()
End If
'End If
End Sub
Private Sub LoadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadToolStripMenuItem.Click
Dim basketFile As StreamReader
Dim gi As GroceryItem
Dim sNo, brand, desc, aisle As String
Dim price As Double
Dim y As Integer
basket.Clear()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFileName = OpenFileDialog1.FileName
basketFile = File.OpenText(strFileName)
' Read Power rating from file
Using sr As StreamReader = New StreamReader(strFileName)
Do While sr.Peek() > -1
For Each c As String In sr.ReadToEnd().Split(CType(Chr(10), Char))
sNo = ""
For Each d As String In c.Split(",")
If y = 0 Then
sNo = d
End If
If y = 1 Then
aisle = d
End If
If y = 2 Then
brand = d
End If
If y = 3 Then
desc = d
End If
If y = 4 Then
price = d
End If
y += 1
Next
If (sNo <> "") Then
gi = New GroceryItem(sNo, brand, price)
gi.Type = [Enum].Parse(GetType(Aisle), aisle)
gi.Description = desc
If (sNo <> "" & vbCr & "") Then
basket.Add(gi)
End If
End If
y = 0
Next
Loop
End Using
basketFile.Close()
End If
End Sub
End Class

i got no error, but : "OleDbException was unhandled Syntax error (missing operator) in query expression" how to solve this?

I am new in creating an application using Visual Stuido 2010 C# and Microsft Access 2007. I am planning to create an application where the user can add data to the database(MS-Access). But I got an error stating that "Syntax Error (missing operator) In Query Expression". I really can't find what's the problem with my code. im using panel for page 2 of my form.
i got the problem from Sub Button1 "rd = cmd.ExecuteReader"
This is my code in adding data to the database:
Imports System.Data.OleDb
Public Class Form1
Dim conn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim str As String
Dim cmd As OleDbCommand
Dim rd As OleDbDataReader
Dim tanya As String
Sub koneksi()
str = "provider=microsoft.jet.oledb.4.0;data source=Database1.mdb"
conn = New OleDbConnection(str)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
End Sub
Sub tampilkan()
da = New OleDbDataAdapter("select * from tb_bpl", conn)
ds = New DataSet
da.Fill(ds, "tb_bpl")
DataGridView1.DataSource = ds.Tables("tb_bpl")
DataGridView1.Columns(1).Width = 250
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call koneksi()
Call tampilkan()
End Sub
Private Sub Button4_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Me.Close()
End Sub
Private Sub bersih()
TextBox1.Clear()
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
TextBox9.Text = ""
TextBox10.Text = ""
TextBox11.Text = ""
TextBox12.Text = ""
TextBox13.Text = ""
TextBox14.Text = ""
TextBox15.Text = ""
TextBox16.Text = ""
TextBox17.Text = ""
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cmd = New OleDbCommand("select * tb_bpl where periode='" + TextBox1.Text + "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If Not rd.HasRows Then 'jika data/baris tidak ditemukan
Dim simpan As String = "insert into tb_bpl(periode, reviewer, pemeriksa, paraf1, paraf2, y1, kkp1, ket1, y2, kkp2, ket2, y3, kkp3, ket3, y4, kkp4, ket4) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & TextBox12.Text & "','" & TextBox13.Text & "','" & TextBox14.Text & "','" & TextBox15.Text & "','" & TextBox16.Text & "','" & TextBox17.Text & "')"
cmd = New OleDbCommand(simpan, conn)
cmd.ExecuteNonQuery()
MsgBox("Data Baru Tersimpan", vbInformation, "Pemberitahuan!!!")
Call bersih()
Else
MsgBox("Data Sudah Ada", vbInformation, "Maaf!!!")
End If
tampilkan()
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
cmd = New OleDbCommand("select * from tb_bpl where periode='" & TextBox1.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
Dim sqledit As String = "update tb_bpl set reviewer='" & TextBox2.Text & "',pemeriksa='" & TextBox3.Text & "',paraf1='" & TextBox4.Text & "',paraf2='" & TextBox5.Text & "',y1='" & TextBox6.Text & "' ,kkp1='" & TextBox7.Text & "' ,ket1='" & TextBox8.Text & "',y2='" & TextBox9.Text & "',kkp2='" & TextBox10.Text & "',ket2='" & TextBox11.Text & "',y3='" & TextBox12.Text & "',kkp3='" & TextBox13.Text & "',ket3='" & TextBox14.Text & "',y4='" & TextBox15.Text & "',kkp4='" & TextBox16.Text & "',ket4='" & TextBox17.Text & "' where periode='" & TextBox1.Text & "'"
cmd = New OleDbCommand(sqledit, conn)
cmd.ExecuteNonQuery()
End If
MsgBox("Data Terubah", vbOKOnly, "Sukses")
Call bersih()
Call tampilkan()
End Sub
Private Sub Button3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
cmd = New OleDbCommand("select * from tb_bpl where periode='" & TextBox1.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
tanya = MsgBox("Anda Yakin Akan Menghapus Data?", vbYesNo, "Perhatian")
If tanya = vbYes Then
Dim sqlhapus As String = "delete * from tb_bpl where periode='" & TextBox1.Text & "'"
cmd = New OleDbCommand(sqlhapus, conn)
cmd.ExecuteNonQuery()
MsgBox("Data Terhapus", vbOKOnly, "Sukses")
Call bersih()
End If
End If
Call tampilkan()
End Sub
Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs)
cmd = New OleDbCommand("select * from tb_bpl where periode='" & TextBox1.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
TextBox2.Text = rd.Item("reviewer")
TextBox3.Text = rd.Item("pemeriksa")
TextBox4.Text = rd.Item("paraf1")
TextBox5.Text = rd.Item("paraf2")
TextBox6.Text = rd.Item("y1")
TextBox7.Text = rd.Item("kkp1")
TextBox8.Text = rd.Item("ket1")
TextBox9.Text = rd.Item("y2")
TextBox10.Text = rd.Item("kkp2")
TextBox11.Text = rd.Item("ket2")
TextBox12.Text = rd.Item("y3")
TextBox13.Text = rd.Item("kkp3")
TextBox14.Text = rd.Item("ket3")
TextBox15.Text = rd.Item("y4")
TextBox16.Text = rd.Item("kkp4")
TextBox17.Text = rd.Item("ket4")
End If
End Sub
End Class

My code throws an error that the connection associated with data reader is not closed

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Con = New MySqlConnection
Con.ConnectionString = "server = localhost; user = root; database= employee"
Try
Con.Open()
If TextBox1.Text = "" And TextBox2.Text = "" And TextBox3.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
Else
Dim theQuery As String = "SELECT * FROM accounts WHERE EmpNo=#EmpNo "
Dim cmd1 As MySqlCommand = New MySqlCommand(theQuery, Con)
cmd1.Parameters.AddWithValue("#EmpNo", TextBox1.Text)
Using reader As MySqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
reader.Close()
Else
' User does not exist, add them
Dim cmd As MySqlCommand = New MySqlCommand("Insert into [ordering].[dbo].[accounts] ([EmpNo],[Username],[password]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "', '" + TextBox3.Text + "')", Con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End If
End Using
End If
Con.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
Con.Dispose()
End Try
End Sub

Resources