syntax error in false clause and when I search for names nothing displays - vb.net

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

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

How to get UPDATE SQL commands working in VB.net and MySQL?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost; username=root; password=; database=wh_db")
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
con.Open()
cmd.Connection = con
cmd.CommandText = " select pass from user where pass ='" & oldpass.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
cmd.Connection = con
cmd.CommandText = " UPDATE user SET pass ='" & newpass.Text & "' where user = '" & user.Text & "'"
Else
MsgBox("Password is not correct")
End If
End Sub
I've not used MySQL for a while but have a look at this. It should give you some start into what you're after:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dr As MySqlDataReader
Using con As New MySqlConnection(yourConnectionString),
cmd As New MySQLCommand("SELECT pass FROM user WHERE pass = #pass", con)
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = oldpass.Text
con.open()
dr = cmd.ExecuteReader
End Using
If dr.HasRows Then
Using con As New MySqlConnection(yourConnectionString),
cmd As New MySQLCommand("UPDATE user SET pass = #pass WHERE user = #user", con)
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = newpass.Text
cmd.Parameters.Add("#user", MySqlDbType.VarChar).Value = user.Text
con.open()
cmd.ExecuteNonQuery()
End Using
Else
MsgBox("Password is not correct")
End If
End Sub
The reason you're not updating is because you haven't told the command to update. I've also implemented Using which I suggest you do and also look at parameters to stop SQL injection.
I've separated both statements into two Using statements as I feel this would be better rather than attempting to reuse the same object for both the SELECT and UPDATE command.

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

Changing DataGridview after filter combobox

I'm trying to refill my DataGridView after a filter selection in a combobox.
Here is my code where I try...at this moment the code is clearing the DataGridview and just fill only on row with only 1 cell..KlantID = 7
Any idea?
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
klantid = ComboBox1.SelectedValue
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim SQLstr As String
SQLstr = "SELECT * FROM tblKlant WHERE KlantID = #klantid"
Dim cmd As New OleDbCommand(SQLstr, myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(ds, "tblKlant")
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblKlant"
DataGridView1.Refresh()
End Sub
Why are you populating records on every combobox_SelectionChange event execution. Try to filter your data only instead of query execution.
And, better to use SelectedValueChanged event instead of SelectionChange.
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
//Fill your data here with DataView
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim cmd As New OleDbCommand("SELECT * FROM tblKlant", myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable() 'Dont use dataset if your are not relating more than one tables
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(dt)
dt.TableName = "tblKlant"
cmd.ExecuteNonQuery()
DataGridView1.DataSource = dt.DefaultView
DataGridView1.DataMember = "tblKlant"
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
End Sub
Private Sub combobox_SelectedValueChanged(sender As Object, e As EventArgs) Handles combobox.SelectedValueChanged
IF combobox.SelectedValue IsNot Nothing Then
Dim dv As DataView = DirectCast(DataGridView1.DataSource, DataView)
dv.RowFilter = "KlantID=" + combobox.SelectedValue.ToString()
Else
dv.RowFilter = vbNullString
End IF
End Sub

specified cast is not valid

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