specified cast is not valid - vb.net

Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.

try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub

Related

Oledb No Value Given for one or more required parameters VB.NET

I can anyone tell me whats wrong with my code? I am a complete novice here and this is the first time I have tried writing something in quite a while,
The below code should be updating two fields in an access database
Private Sub TestButton_Click(sender As Object, e As EventArgs) Handles TestButton.Click
'connects application to database
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DatabasePath\database.accdb"
Dim SqlString As String = "update SaintStaff set [StaffHours]=[#CAHours],[RecordedTime]=[#Time] where [StaffName] = " & Label2.Text & ""
'updates record in SaintStaff table.
Using conn As New OleDbConnection(ConnString)
conn.Open()
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("[#CAHours]", Label6.Text)
cmd.Parameters.AddWithValue("[#Time]", Label10.Text)
cmd.ExecuteNonQuery()
End Using
conn.Close()
End Using
End Sub
I am getting the following error
System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
and its highlighting the cmd text on each line, I cant tell what I am doing wrong, can anyone help?
Thank you
This Question was answered by MatSnow and olivier-jacot-descombes in the comments, the correct code looks as follows
Private Sub TestButton_Click(sender As Object, e As EventArgs) Handles TestButton.Click
'connects application to database
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DatabasePath\Database.accdb"
Dim SqlString As String = "update SaintStaff set StaffHours = #CAHours, RecordedTime = #Time where StaffName = #staffname "
'updates record in SaintStaff table.
Using conn As New OleDbConnection(ConnString)
conn.Open()
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CAHours", OleDbType.VarChar).Value = Label6.Text
cmd.Parameters.Add("#Time", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#Staffname", OleDbType.VarChar).Value = Label2.Text
cmd.ExecuteNonQuery()
End Using
conn.Close()
End Using
End Sub

syntax error in false clause and when I search for names nothing displays

One time when I run this code it run smoothly but then when i search for names there is no record appears. Badly need your help guys for our program project. thanks in advance :)
This is my code :
Private Sub search_btn_Click(sender As Object, e As EventArgs) Handles search_btn.Click
Me.Show()
Search_Record()
End Sub
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\VB\HSU\HSU\G11B.mdb"
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT Last_Name, First_Name FROM 10ABM"
sSQL = sSQL & "WHERE Last_Name like '%" & Me.search_txt.Text & "%'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub

Visual Basic ACCDB File Read for Cascading Combo Box

So I've got an access database with three columns in: Manufacture, Fixture and Mode
I'm using the code below to create cascading combo boxes in my form.
Imports System.Data.OleDb
Public Class Add_Fixtures
Dim con As New OleDbConnection
Dim constring As String
Dim cmd As New OleDbCommand
Dim dr As OleDbDataReader
Dim cmd1 As New OleDbCommand
Dim dr1 As OleDbDataReader
Dim cmd2 As New OleDbCommand
Dim dr2 As OleDbDataReader
Private Sub Add_Fixtures_Load(sender As Object, e As EventArgs) Handles Me.Load
constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/FixtureLibrary.accdb"
With con
.ConnectionString = constring
.Open()
End With
With cmd
.Connection = con
.CommandType = CommandType.Text
.CommandText = "SELECT DISTINCT Fixtures.Manufacture from Fixtures;"
End With
dr = cmd.ExecuteReader()
While dr.Read
cbManufacture.Items.Add(dr("Manufacture"))
End While
With cmd1
.Connection = con
.CommandType = CommandType.Text
.CommandText = "SELECT from Fixtures where [Manufacture]='" & Me.cbManufacture.Text & "';"
End With
dr1 = cmd1.ExecuteReader()
While dr1.Read
cbFixture.Items.Add(dr1("Fixture"))
End While
With cmd2
.Connection = con
.CommandType = CommandType.Text
.CommandText = "SELECT DISTINCT Fixtures.Mode from Fixtures where [Fixture] ='" & Me.cbFixture.Text & "';"
End With
dr2 = cmd2.ExecuteReader()
While dr2.Read
cbMode.Items.Add(dr2("Mode"))
End While
End Sub
End Class
But on this line: dr1 = cmd1.ExecuteReader()
I get this error
System.Data.OleDb.OleDbException: 'The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.'
Anyone have any ideas why or what is causing it?
Cheers
You don't select any field(s), and property Text is only valid for the control having focus, so:
.CommandText = "SELECT * from Fixtures where [Manufacture]='" & Me.cbManufacture.Value & "';"

Setting a variable to the highest value in Access Database ASP.NET

I want to set a variable to a value in an Access Database table from aspx.vb. I want to return the highest "PalletNumber" to txbPalletNumber textbox. What am I doing wrong?
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim cmd As New OleDbCommand
Try
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT PalletNumber, MAX(PalletNumber) FROM
tblPalletNumber"
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
Catch ex As Exception
'Error handling
End Try
txbPackday.Text = DateAndTime.Now
End Sub
Here is the solution. Thanks for all the help.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim test As String
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
Dim cmd As New OleDbCommand
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT MAX(PalletNumber) FROM tblPalletNumber"
test = cmd.ExecuteScalar()
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
txbPackday.Text = DateAndTime.Now
End Sub

Delete From Table error

i'm trying to create a delete button to delete a record ....
here's my code:
Dim SqlQuery As String = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
'id is public shared as integer , which is ListView1.SelectedItems(0).Text
Dim SqlCommand As New OleDb.OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
I get an exception in .ExecuteNonQuery(), the error is
"ExecuteNonQuery() requires the command to have a transaction" ,
"Validate transaction" , "ExecuteReaderInternal"
assume that the database is connected, got info and delete button is button3 .
Also i will show you my whole form code:
Public Class Report
Public id As Integer
Public conn As New OleDb.OleDbConnection
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ramy\Documents\Beach.accdb"
Private Property RivieraDataSet As Object
Private Sub Report_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
conn.Close()
End Sub
Private Sub Report_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If conn.State = ConnectionState.Closed Then
Try
conn.ConnectionString = connstring
conn.Open()
MsgBox("DataBase opened successfully!", MsgBoxStyle.Exclamation)
loadlistview()
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.Critical)
End Try
Else
MsgBox("DataBase Error!!", MsgBoxStyle.Critical)
End If
Dim reading As OleDb.OleDbDataReader
Dim cmd As New OleDb.OleDbCommand
Dim trans As OleDb.OleDbTransaction
trans = conn.BeginTransaction
cmd.CommandText = "SELECT * FROM MyTable"
cmd.Connection = conn
cmd.Transaction = trans
reading = cmd.ExecuteReader
Dim i
Do While reading.Read
i = Val(reading.Item("Total")) + i
Loop
TextBox7.Text = i
TextBox7.Text = Convert.ToDecimal(TextBox7.Text).ToString("N2") & " L.E"
End Sub
Sub loadlistview()
ListView1.FullRowSelect = True
ListView1.MultiSelect = False
ListView1.View = View.Details
ListView1.Columns.Clear()
ListView1.Items.Clear()
ListView1.Columns.Add("No", 30, HorizontalAlignment.Left)
ListView1.Columns.Add("InvoiceDate", 125, HorizontalAlignment.Left)
ListView1.Columns.Add("PersonsNumber", 70, HorizontalAlignment.Left)
ListView1.Columns.Add("PersonPrice", 80, HorizontalAlignment.Left)
ListView1.Columns.Add("CashierName", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("Total", 100, HorizontalAlignment.Left)
Dim SqlQuery As String = "SELECT * FROM MyTable"
Dim SqlCommand As New OleDb.OleDbCommand
Dim SqlAdapter As New OleDb.OleDbDataAdapter
Dim table As New DataTable
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
.Fill(table)
End With
For i = 0 To table.Rows.Count - 1
With ListView1
.Items.Add(table.Rows(i)("InvoiceNumber"))
With .Items(.Items.Count - 1).SubItems
.Add(table.Rows(i)("InvoiceDate"))
.Add(table.Rows(i)("PersonsNumber"))
.Add(table.Rows(i)("PersonPrice"))
.Add(table.Rows(i)("CashierName"))
.Add(table.Rows(i)("Total"))
End With
End With
Next
End Sub
Private Sub ListView1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView1.MouseClick
Dim SqlQuery As String = "SELECT * FROM MyTable"
Dim SqlCommand As New OleDb.OleDbCommand
Dim SqlAdapter As New OleDb.OleDbDataAdapter
Dim table As New DataTable
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
End With
If ListView1.SelectedItems.Count > 0 Then
id = ListView1.SelectedItems(0).Text
TextBox1.Text = id
TextBox6.Text = ListView1.SelectedItems(0).SubItems(1).Text
TextBox3.Text = ListView1.SelectedItems(0).SubItems(2).Text
TextBox4.Text = ListView1.SelectedItems(0).SubItems(3).Text
TextBox2.Text = ListView1.SelectedItems(0).SubItems(4).Text
TextBox5.Text = ListView1.SelectedItems(0).SubItems(5).Text
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim SqlQuery As String = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
'id is public shared as integer , which is ListView1.SelectedItems(0).Text
Dim SqlCommand As New OleDb.OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
End Sub
End Class
I was searching for a mistake in my delete btn code for hours , but i can see everything is good..... but .ExecuteNonQuery() is so annoying .
In your Form_Load you open a transaction for your GLOBAL connection.
This means that every command executed using that connection should be informed of this transaction (and you do it in the Form_Load event setting the Command.Transaction property).
But in other parts of your program, executing a command with that connection and not setting the Transaction property will raise the mentioned error.
Looking at your code above I would suggest to remove altogether the Transaction because, as is, you don't need it.
Simply remove these lines in Form_Load
Dim trans As OleDb.OleDbTransaction
trans = conn.BeginTransaction
...
cmd.Transaction = trans
Instead, if for motives not apparent from the code above, you insist in keeping the Transaction then you should create the command from the connection so the transaction is passed to the command.
Dim SqlQuery As String = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
Dim SqlCommand = conn.CreateCommand()
With SqlCommand
....
End With
By the way, I really suggest you to remove that global connection variable. It is only a source of problems (check if open, transactions etc...) Just make a function that creates it for you and use it in a Using Statement whenever you need it
Public Function GetConnection() As OleDb.OleDbConnection
Dim conn = New OleDb.OleDbConnection(connstring)
conn.Open()
return conn
End Function
And use it with Using Statement that close and dispose the enclosed object also in case of exceptions
Using conn = GetConnection()
Using command = conn.CreateCommand()
With command
command.CommandText = "DELETE FROM MyTable WHERE InvoiceNumber = " & id & ";"
command.ExecuteNonQuery()
End With
End Using
End Using
Pay also attention at possible sql injection scenarios. In your situation (reading an integer from a ListView) there are few problems, but a parameterized query is always better