I'm trying to figure out how to update a selected row in my DataGridView. I would like my system to recognize an existing row of information I've selected from my datagridview (I've set it to full row select btw) and update/edit the information by changing them with the textboxes and comboboxes I used to add them. Everything in my table is set as Text datatype, besides ID which is auto number. However, I get an error with the code I used below. Any help will be greatly appreciated! Thank you :) (I'm gonna provide a link to the screenshot of the error since I don't have enough reputation.)
* New error when I enclose Section with brackets
http://i.imgur.com/gs8rVhB.png
Imports System.Data.OleDb
Public Class AdmMain
Dim con As New OleDbConnection
Sub fillcombo()
strsql = " select yrgr from yearandgrade"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cboyr.Items.Add(acsdr("yrgr"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Sub comb2()
strsql = " select sections from sectio"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cbosec.Items.Add(acsdr("sections"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
Me.Close()
LoginUser.Show()
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.TxtID.Text = ""
Me.txtFName.Text = ""
Me.txtMName.Text = ""
Me.txtLName.Text = ""
Me.cboyr.Text = ""
Me.cbosec.Text = ""
Me.TxtID.Focus()
End Sub
Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Module1.connect()
Me.fillcombo()
Me.comb2()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Thesis\Thesis\Database1.accdb"
con.Open()
datagridshow()
End Sub
Private Sub datagridshow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("select * from students ", con)
da.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "INSERT INTO students " & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#studid", TxtID.Text)
cmd.Parameters.AddWithValue("#fname", txtFName.Text)
cmd.Parameters.AddWithValue("#mname", txtMName.Text)
cmd.Parameters.AddWithValue("#lname", txtLName.Text)
cmd.Parameters.AddWithValue("#yr", rbdtext)
cmd.Parameters.AddWithValue("#sec", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully added!", "Added!")
datagridshow()
Else
MessageBox.Show("Failure to add new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub TxtID_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtID.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "UPDATE Students SET StudentID = #STUDID, FirstName = #FNAME, MiddleName = #MNAME, LastName= #LNAME, Yr = #YRR, [Section] = #SEC WHERE StudentID = #STUDID, FirstName =#FNAME, MiddleName = #MNAME, LastName= #LNAME, Yr = #YRR, [Section] = #SEC"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#STUDID", TxtID.Text)
cmd.Parameters.AddWithValue("#FNAME", txtFName.Text)
cmd.Parameters.AddWithValue("#MNAME", txtMName.Text)
cmd.Parameters.AddWithValue("#LNAME", txtLName.Text)
cmd.Parameters.AddWithValue("#YRR", rbdtext)
cmd.Parameters.AddWithValue("#SEC", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully updated!", "Updated!")
datagridshow()
Else
MessageBox.Show("Failure to update new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
The syntax of a UPDATE...WHERE expression requires a condition that uniquely identifies the record to UPDATE. If the condition is an expression composed of more than one field/value then these conditions should be combined using AND or OR operators not using commas.
Usually the condition in the WHERE clause identifies the record to be updated using the PRIMARY KEY of the table (in your case this seems to be the StudentID field) so you just need to write
Dim sqlquery As String = "UPDATE Students SET FirstName = #FNAME, " &_
"MiddleName = #MNAME, LastName= #LNAME, Yr = #YRR, " & _
"[Section] = #SEC " & _
"WHERE StudentID = #STUDID"
Note that if StudentID is the PRIMARYKEY you don't try to change/update it bacause this could cause inconsistencies in your other database tables that refer (have a relationship) with the Students table
Finally, the OleDb provider don't recognize the parameter by their name, the provider expects that each parameter passed is in the same order in which the parameter placeholders appears in the command text (It use the position of the parameter to pass the value to the database engine), so you need to change also the order in which you set up the parameter collection for the UPDATE
cmd.Parameters.AddWithValue("#FNAME", txtFName.Text)
cmd.Parameters.AddWithValue("#MNAME", txtMName.Text)
cmd.Parameters.AddWithValue("#LNAME", txtLName.Text)
cmd.Parameters.AddWithValue("#YRR", rbdtext)
cmd.Parameters.AddWithValue("#SEC", uno)
cmd.Parameters.AddWithValue("#STUDID", TxtID.Text)
Related
Here is the full code
Imports System.Data.OleDb
Public Class veterinarycgpa
Private Sub veterinarycgpa_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matricno, sessionad As String
matricno = pretranscript.matric.Text
sessionad = pretranscript.session.Text
'semester = checkresult.semester.Text
Dim allunit, allwgp As Decimal
Try
Dim con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=cgpa.accdb")
Dim cmd As New System.Data.OleDb.OleDbCommand
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim dr As OleDbDataReader
cmd.CommandText = System.Data.CommandType.Text
Dim str As String
str = "SELECT [fullname],[matric], [maiden_name], [gender], [session_admitted], [mode_of_entry], [programme] FROM student WHERE [matric]='" & matricno & "' AND [session_admitted] = '" & sessionad & "' "
Dim cd As OleDbCommand = New OleDbCommand(str, con)
dr = cd.ExecuteReader
dr.Read()
If dr("matric") = pretranscript.matric.Text Then 'checkresult.matric.Text
fullname.Text = dr("fullname").ToString
matric.Text = dr("matric").ToString
mname.Text = dr("maiden_name").ToString
session.Text = dr("session_admitted").ToString
gender.Text = dr("gender").ToString
mode_of_entry.Text = dr("mode_of_entry").ToString
programme.Text = dr("programme").ToString
End If
'MsgBox("No Result found for the given matric no and session", MsgBoxStyle.Critical)
con.Close()
If con.State = ConnectionState.Closed Then
con.Open()
End If
str = " SELECT [matric], [session], [pvp711] ,[pvp713] ,[pvp719] ,[pvp703] ,[pvp715], [pvp717], [pvp701] FROM veterinaryone WHERE [matric]='" & matricno & "' AND [session] = '" & sessionad & "'"
Dim cd1 As OleDbCommand = New OleDbCommand(str, con)
dr = cd1.ExecuteReader
dr.Read()
If dr("matric") = pretranscript.matric.Text Then
score1.Text = dr("pvp711").ToString
score2.Text = dr("pvp713").ToString
score3.Text = dr("pvp719").ToString
score4.Text = dr("pvp703").ToString
score5.Text = dr("pvp715").ToString
score6.Text = dr("pvp717").ToString
score7.Text = dr("pvp701").ToString
End If
con.Close()
If con.State = ConnectionState.Closed Then
con.Open()
End If
str = " SELECT [matric], [session], [pvp710] ,[pvp712] ,[pvp714] ,[pvp716] ,[pvp702], [pvp704], [pvp718], [pvp722], [pau3101], [pau3104] FROM veterinarytwo WHERE [matric]='" & matricno & "' AND [session] = '" & sessionad & "'"
Dim cd2 As OleDbCommand = New OleDbCommand(str, con)
dr = cd2.ExecuteReader
dr.Read()
If dr("matric") = pretranscript.matric.Text Then
score8.Text = dr("pvp710").ToString
score9.Text = dr("pvp712").ToString
score10.Text = dr("pvp714").ToString
score11.Text = dr("pvp716").ToString
score12.Text = dr("pvp702").ToString
score13.Text = dr("pvp704").ToString
score14.Text = dr("pvp718").ToString
score15.Text = dr("pvp722").ToString
score16.Text = dr("pau3101").ToString
score17.Text = dr("pau3104").ToString
End If
con.Close()
If con.State = ConnectionState.Closed Then
con.Open()
End If
str = " SELECT [matric], [session], [pvp721] FROM veterinarythree WHERE [matric]='" & matricno & "' AND [session] = '" & sessionad & "'"
Dim cd3 As OleDbCommand = New OleDbCommand(str, con)
dr = cd3.ExecuteReader
dr.Read()
If dr("matric") = pretranscript.matric.Text Then
score18.Text = dr("pvp721").ToString
End If
con.Close()
If con.State = ConnectionState.Closed Then
con.Open()
End If
str = " SELECT [matric], [session], [pvp720], [pvp724] FROM veterinaryfour WHERE [matric]='" & matricno & "' AND [session] = '" & sessionad & "'"
Dim cd4 As OleDbCommand = New OleDbCommand(str, con)
dr = cd4.ExecuteReader
dr.Read()
If dr("matric") = pretranscript.matric.Text Then
score19.Text = dr("pvp720").ToString
score20.Text = dr("pvp724").ToString
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "ALERT")
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Visible = False
Button2.Visible = False
PrintPreviewDialog1.Document = PrintDocument1
'PrintPreviewDialog1.PrintPreviewControl.Zoom = 1
PrintPreviewDialog1.ShowDialog()
'PrintDocument1.DefaultPageSettings.Landscape = True
PrintDocument1.Print()
Button1.Visible = True
Button2.Visible = True
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim groupbox As New Bitmap(Me.Width, Me.Height)
Me.DrawToBitmap(groupbox, New Rectangle(0, 0, Me.Width, Me.Height))
e.Graphics.DrawImage(groupbox, 0, 0)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
I have other forms containing code like this as well, so if I print from this, it print to PDF automatically successfully, but if I close the form and open it again or any other form to print the second time then it breaks and brings about this error.
First-chance exception at 0x5adf7ecf (dui70.dll) in Pau_CGPA.exe: 0xC0000005: Access violation reading location 0x0000001c.
Unhandled exception at 0x5adf7ecf (dui70.dll) in Pau_CGPA.exe: 0xC000041D: 0xC000041D: An unhandled exception was encountered during a user callback.
So I don't know what is wrong.
Here's some points to consider:
Use the same objects as long as that is possible. No need to create new OleDbCommand cd1, cd2, ..etc. Just create one and reuse it by changing its CommandText and update its Parameters.
Always use parameterized queries and avoid string concatenating the SQL statements like WHERE [matric]='" & matricno.
When you create a new OleDbConnection the connection remains closed until you call the Open method explicitly. So checking the connection State just right after creating the object doesn't make any sense.
Keep the connection opened as long as you need to use the same connection again and again. So no need to close and reopen it.
The Read method and the HasRows property both return True if the OleDbDataReader has something to read.
You should dispose the disposable objects, always create them in Using blocks.
Now, applying that on the Load event block would produce:
Imports System.Data.OleDb
Imports System.Drawing.Printing
'...
Private Sub veterinarycgpa_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matricno = pretranscript.matric.Text
Dim sessionad = pretranscript.session.Text
Try
Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=cgpa.accdb"),
cmd As New OleDbCommand("SELECT [fullname], [matric], [maiden_name], [gender], [session_admitted], [mode_of_entry], [programme] FROM [student] WHERE [matric] = ? AND [session_admitted] = ?", con)
'Better to use the Add(..) method instead and define the right OleDbType and size...
cmd.Parameters.AddWithValue("matric", matricno)
cmd.Parameters.AddWithValue("session_admitted", sessionad)
con.Open()
Using dr = cmd.ExecuteReader
If dr.Read() Then
fullname.Text = dr("fullname").ToString
matric.Text = dr("matric").ToString
mname.Text = dr("maiden_name").ToString
session.Text = dr("session_admitted").ToString
gender.Text = dr("gender").ToString
mode_of_entry.Text = dr("mode_of_entry").ToString
programme.Text = dr("programme").ToString
End If
End Using
cmd.Parameters.Clear()
cmd.CommandText = "SELECT [matric], [session], [pvp711], [pvp713], [pvp719], [pvp703], [pvp715], [pvp717], [pvp701] FROM [veterinaryone] WHERE [matric] = ? AND [session] = ?"
cmd.Parameters.AddWithValue("matric", matricno)
cmd.Parameters.AddWithValue("session", sessionad)
Using dr = cmd.ExecuteReader
If dr.Read() Then
score1.Text = dr("pvp711").ToString
score2.Text = dr("pvp713").ToString
score3.Text = dr("pvp719").ToString
score4.Text = dr("pvp703").ToString
score5.Text = dr("pvp715").ToString
score6.Text = dr("pvp717").ToString
score7.Text = dr("pvp701").ToString
End If
End Using
cmd.Parameters.Clear()
cmd.CommandText = "SELECT [matric], [session], [pvp710], [pvp712], [pvp714], [pvp716], [pvp702], [pvp704], [pvp718], [pvp722], [pau3101], [pau3104] FROM [veterinarytwo] WHERE [matric] = ? AND [session] = ?"
cmd.Parameters.AddWithValue("matric", matricno)
cmd.Parameters.AddWithValue("session", sessionad)
Using dr = cmd.ExecuteReader
If dr.Read() Then
score8.Text = dr("pvp710").ToString
score9.Text = dr("pvp712").ToString
score10.Text = dr("pvp714").ToString
score11.Text = dr("pvp716").ToString
score12.Text = dr("pvp702").ToString
score13.Text = dr("pvp704").ToString
score14.Text = dr("pvp718").ToString
score15.Text = dr("pvp722").ToString
score16.Text = dr("pau3101").ToString
score17.Text = dr("pau3104").ToString
End If
End Using
cmd.Parameters.Clear()
cmd.CommandText = "SELECT [matric], [session], [pvp721] FROM [veterinarythree] WHERE [matric] = ? AND [session] = ?"
cmd.Parameters.AddWithValue("matric", matricno)
cmd.Parameters.AddWithValue("session", sessionad)
Using dr = cmd.ExecuteReader
If dr.Read() Then
score18.Text = dr("pvp721").ToString
End If
End Using
cmd.Parameters.Clear()
cmd.CommandText = "SELECT [matric], [session], [pvp720], [pvp724] FROM [veterinaryfour] WHERE [matric]= ? AND [session] = ?"
cmd.Parameters.AddWithValue("matric", matricno)
cmd.Parameters.AddWithValue("session", sessionad)
Using dr = cmd.ExecuteReader
If dr.Read() Then
score19.Text = dr("pvp720").ToString
score20.Text = dr("pvp724").ToString
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "ALERT")
End Try
End Sub
As for the printing part:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintDialog1.Document = PrintDocument1
If PrintDialog1.ShowDialog = DialogResult.OK Then
PrintDialog1.Document.Print()
End If
End Sub
Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
Button1.Visible = False
Button2.Visible = False
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
Using bmp As New Bitmap(Width, Height)
DrawToBitmap(bmp, New Rectangle(0, 0, Width, Height))
e.Graphics.DrawImage(bmp, 0, 0)
'You might want to try:
'e.Graphics.DrawImage(bmp, ea.PageBounds.X, ea.PageBounds.Y, ea.PageBounds.Width, ea.PageBounds.Height)
'e.Graphics.DrawImage(bmp, ea.MarginBounds.X, ea.MarginBounds.Y, ea.MarginBounds.Width, ea.MarginBounds.Height)
End Using
End Sub
Private Sub PrintDocument1_EndPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.EndPrint
Button1.Visible = True
Button2.Visible = True
End Sub
Accordingly, you can delete both the PrintPreviewDialog1 and PrintDocument1. And don't forget to delete the PrintDocument1_PrintPage handler.
I'm trying to get my system to insert combo box values into my access database. I always get this very long error whenever I try to click my 'add' button and I somehow get this feeling that it's because of my INSERT statement. This is my whole code for my form. Any help will be greatly appreciated! Thank you
Imports System.Data.OleDb
Public Class AdmMain
Sub fillcombo()
strsql = " select yrgr from yearandgrade"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cboyr.Items.Add(acsdr("yrgr"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Sub comb2()
strsql = " select sections from sectio"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cbosec.Items.Add(acsdr("sections"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
Me.Close()
LoginUser.Show()
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.txtFName.Text = ""
Me.txtMName.Text = ""
Me.txtLName.Text = ""
Me.cboyr.Text = ""
Me.cbosec.Text = ""
Me.txtFName.Focus()
End Sub
Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Module1.connect()
Me.fillcombo()
Me.comb2()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database1.accdb"
conn.Open()
Dim sqlquery As String = "INSERT INTO students (StudentID, FirstName,MiddleName,LastName,Yr, Section) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
Dim SqlCommand As New System.Data.OleDb.OleDbCommand
SqlCommand.Parameters.AddWithValue("#studid", TxtID.Text)
SqlCommand.Parameters.AddWithValue("#fname", txtFName.Text)
SqlCommand.Parameters.AddWithValue("#mname", txtMName.Text)
SqlCommand.Parameters.AddWithValue("#lname", txtLName.Text)
SqlCommand.Parameters.AddWithValue("#yr", rbdtext)
SqlCommand.Parameters.AddWithValue("#sec", uno)
SqlCommand.Connection = conn
Dim sqlRead As System.Data.OleDb.OleDbDataReader = SqlCommand.ExecuteReader()
MsgBox("One record successfully added!", "Added!")
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Heres the error the keeps showing btw!
http://i.imgur.com/DgjiWqm.png
It looks like you are never assigning a select statement to SqlCommand inside your btnAdd_Click method. Try adding SqlCommand.CommandText = sqlquery.
You need to change your query in this way
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "INSERT INTO students " & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlQuery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#studid", TxtID.Text)
cmd.Parameters.AddWithValue("#fname", txtFName.Text)
cmd.Parameters.AddWithValue("#mname", txtMName.Text)
cmd.Parameters.AddWithValue("#lname", txtLName.Text)
cmd.Parameters.AddWithValue("#yr", rbdtext)
cmd.Parameters.AddWithValue("#sec", uno)
Dim rowsInserted = cmd.ExecuteNonQuery()
if rowsInserted > 0 Then
MessageBox.Show("One record successfully added!", "Added!")
else
MessageBox.Show("Failure to add new record!", "Failure!")
End if
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
I have changed the name of your OleDbCommand object to avoid unnecessary confusion with the class SqlCommand used in SqlClient namespace (Not strictly necessary but nevertheless confusing when reading your code). Then I have used the OleDbCommand constructor that gets both the command text and the connection to be used by your command. This avoids to forget setting these essential properties, finally SECTION is a reserved keyword for MS-Access, thus, when used in query text, you need to encapsulate it between square brackets otherwise you get a SYNTAX ERROR
I have Database Software I am trying to make. The problem is I can't seem to find how to make this work, i'm new to this whole thing and have figured a lot out on my own but I can't seem to do this simple task?
I have a listView that displays the data from the SQl everything works great EXCEPT I need the dropdaown box the say yes or no but import into the SQL database a 1 or 0 and also in my list view i need it to display a Yes or a No instead of a 1 or a 0 ? Thanks IN Advance
Code:
Imports System.Data.SqlClient
Imports System.Data
Public Class cmListAll
Dim cn As New SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Private Sub frmReg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With Me.cboActive
.Items.Add("Yes")
.Items.Add("No")
.SelectedIndex = 0
End With
Call connectMeToSQLServer("Data Source=Database;Initial Catalog=db_XXX;Integrated Security=False;Uid=sa; Pwd=PASS;")
Call showList()
End Sub
Private Sub cboActive_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
e.Handled = True
End Sub
Private Sub cboACTIVE_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.txtCredentials.Focus()
End Sub
Sub connectMeToSQLServer(ByVal cnString As String)
Try
With cn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = cnString
.Open()
End With
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Function INC() As Boolean
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Or TypeOf t Is ComboBox Then
End If
If t.Text = "" Then
INC = True
End If
Next
End Function
Sub showList()
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers]"
dr = cmd.ExecuteReader
Me.ListView1.Items.Clear()
While dr.Read
With Me.ListView1
.Items.Add(dr(0))
With .Items(.Items.Count - 1).SubItems
.Add(dr(1))
.Add(dr(2))
.Add(dr(3))
.Add(dr(4))
End With
End With
End While
dr.Close()
End Sub
Sub clearMe()
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
Me.cmdNew.Enabled = True
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = False
Me.cmdDelete.Enabled = False
Me.cboActive.SelectedIndex = 0
End If
Next
End Sub
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
End If
Next
Me.cmdNew.Enabled = False
Me.cmdSave.Tag = "SAVE"
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = True
Me.GroupBox2.Enabled = True
Me.txtfirstname.Focus()
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Select Case Me.cmdSave.Tag
Case "SAVE"
If INC() = True Then
MsgBox("Please Complete All Fields!", MsgBoxStyle.Exclamation, "")
Exit Sub
Else
cmd = New SqlCommand
cmd.CommandText = "Insert Into [Case Managers](Firstname,Lastname,Credentials,Active) Values('" & Me.txtfirstname.Text & "', '" & Me.txtlastname.Text & "', '" & Me.txtCredentials.Text & "', '" & Me.cboActive.Text & "' )"
cmd.Connection = cn
cmd.ExecuteNonQuery()
MsgBox("Successfully Save!", MsgBoxStyle.Information, "")
End If
Case Else
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Update [Case Managers] Set firstname='" & Me.txtfirstname.Text & "', lastname='" & Me.txtlastname.Text & "', credentials='" & Me.txtCredentials.Text & "', active='" & Me.cboActive.Text & "' Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & ""
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "")
End Select
clearMe()
showList()
End Sub
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers] Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & " "
dr = cmd.ExecuteReader
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = dr(4)
dr.Close()
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
If MsgBox("Delete This Record?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Delete from [Case Managers] Where CaseMangerID =" & Me.ListView1.SelectedItems(0).Text & " "
cmd.ExecuteNonQuery()
MsgBox("Successfully Deleted!", MsgBoxStyle.Information, "")
Me.cmdDelete.Enabled = False
Me.cmdSave.Enabled = False
Call clearMe()
Call showList()
Else
Exit Sub
End If
End Sub
I assume you're looking at this line:
Me.cboActive.Text = dr(4)
? That's the only thing that looked to me like it might be displaying a yes/no field. You could just put a simple If/Else block there, but as there are several other significant flaws in how this code is structured, I thought it would be useful to re-write that whole method for you:
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
'Would be better to specify column names here
Dim sql As String = "Select * from [Case Managers] Where CaseMangerID = #CaseManager"
'Best practices in most cases call for creating a new connection object for each query
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'This is how to do string substitution in sql to protect against sql injection
cmd.Parameters.Add("#CaseManager", SqlDbType.Int).Value = CInt(Me.ListView1.SelectedItems(0).Text)
Using dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = If(dr(4)=0,"No","Yes")
dr.Close()
End Using
End Using 'No need to close the connection. The Using block takes care of it
'The old code would have the left the connection open if an exception was thrown,'
' which could eventually lock you out of the database
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
You'll need to do something similar later on to invert this for updates/inserts.
You can use DisplayMember/ValueMember pair:
Dim dict As New Dictionary(Of Integer, String)
dict.Add(0, "No")
dict.Add(1, "Yes")
With Me.cboActive
.DisplayMember = "Value"
.ValueMember = "Key"
.DataSource = dict.ToList()
.SelectedIndex = 0
End With
Dictionary may not the best choice of class here, but works as a proof of concept.
Then just use cboActive.SelectedValue and pass that to the SQL query.
i got 2 forms... Dress_Price is for displaying the data form database ( MS Access 2007 ) another form,Edit_Dress is to edit and update the database..
the code successfully updated the data based on the changes from the form Edit_Dress.. but there is 2 problems -
the dgvCustomerDressPrice did not refreshed after updating..
there is "space" being added to the record after updated..
before update price value
Dress_Name = "Tuxedo" Dress_Price = "150"
after update price value
Dress_Name = " Tuxedo" Dress_Price = " 250"
the "space" keeps being added up everytime i update the record... so the search function cant work properly because of the space..
code on Dress_Price :-
Private Sub Dress_Price_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\TMS Final\TMS Final\db\db_TMS.accdb"
con.Open()
dgvCustomerDressPrice()
End Sub
Private Sub dgvCustomerDressPrice()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress", con)
da.Fill(dt)
dgvDressPrice.DataSource = dt.DefaultView
dgvDressPrice.SelectionMode = DataGridViewSelectionMode.FullRowSelect
con.Close()
End Sub
Private Sub btnEditDress_Click(sender As Object, e As EventArgs) Handles btnEditDress.Click
If dgvDressPrice.Rows.Count > 0 Then ' when user click a row, any query for database will based on Order_ID
If dgvDressPrice.SelectedRows.Count > 0 Then
Dim intDressID As Integer = dgvDressPrice.SelectedRows(0).Cells("Dress_ID").Value
Try
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress WHERE Dress_ID =" & intDressID, con)
' the record that will be edited is based on the Customer_ID of particular row clicked
Dim dt As New DataTable
da.Fill(dt)
Edit_Dress.txtDressID.Text = intDressID
Edit_Dress.txtDressName.Text = dt.Rows(0).Item("Dress_Name")
Edit_Dress.txtDressPrice.Text = dt.Rows(0).Item("Dress_Price")
' pass the data from tbl_user into each represented field
Catch ex As Exception
MessageBox.Show("Failed to edit data ! System eror : " & ex.ToString, "Eror !", MessageBoxButtons.OK)
End Try
End If
End If
Edit_Dress.Show()
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress WHERE Dress_Name like '" & txtSearch.Text & "%' ", con)
Dim dt As New DataTable
da.Fill(dt)
dgvCustomerDressPrice().DataSource = dt
con.Close()
End Sub
code on Edit_Dress :-
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\TMS Final\TMS Final\db\db_TMS.accdb")
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim intDressID As Integer
intDressID = Convert.ToInt32(txtDressID.Text)
intDressID = Integer.Parse(txtDressID.Text)
Dim intDressPrice As Integer
intDressPrice = Convert.ToInt32(txtDressPrice.Text)
intDressPrice = Integer.Parse(txtDressPrice.Text)
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ' " & txtDressName.Text & " ' , Dress_Price = ' " & intDressPrice & " ' WHERE Dress_ID = " & intDressID & " "
Dim cmd As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
MessageBox.Show("Data updated !", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Dress_Price.RefreshPriceList()
con.Close()
Me.Close()
Catch ex As Exception
MessageBox.Show("Failed to save into database ! System eror : " & ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Looking at your UPDATE method it is clear why you have a space added every time. You put it in the update string.
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ' " & _
^ here
txtDressName.Text & " ' , Dress_Price = ' " & _
^here ^here
intDressPrice & " ' WHERE Dress_ID = " & intDressID & " "
^here
A part from the simple error that could be fixed removing the space, this is not the correct way to create an update command. You should use a parameterized query
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
con = New OleDb.OleDbConnection(.....)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim intDressID As Integer
intDressID = Convert.ToInt32(txtDressID.Text)
Dim intDressPrice As Integer
intDressPrice = Convert.ToInt32(txtDressPrice.Text)
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ?, Dress_Price = ? " & _
"WHERE Dress_ID = ?"
Dim cmd As New OleDb.OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#p1", txtDressName.Text)
cmd.Parameters.AddWithValue("#p2", intDressPrice)
cmd.Parameters.AddWithValue("#p3", intDressID)
cmd.ExecuteNonQuery()
.....
I can't Search and Edit using this Code. Insert is working. But Insert coding method is not sure (fileContent.ToString). And Search part and Update part is not working.
Dim fileContent As Byte() = My.Computer.FileSystem.ReadAllBytes(OpenFileDialog1.FileName)
Sub NormalUpdate(ByVal _Query)
con.Open()
Dim cmdUpdate As New SqlCommand(_Query)
cmdUpdate.Connection = con
cmdUpdate.CommandType = CommandType.Text
cmdUpdate.ExecuteNonQuery()
con.Close()
End Sub
Sub NormalSave(ByVal _Query)
con.Open()
Dim cmdSave As New SqlCommand(_Query)
cmdSave.Connection = con
cmdSave.CommandType = CommandType.Text
cmdSave.ExecuteNonQuery()
con.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
NormalSave("Insert into Registration values('" + txtMemberNo.Text + "','" + fileContent.ToString + "')")
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
Using cmd As New SqlClient.SqlCommand("Select MemberPicture From Registration where MemberNo = '" + txtMemberNo.Text + "'", con)
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
Using dt As New DataTable
dt.Load(dr)
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row("MemberPicture"), Byte()))
Dim img As Image = Image.FromStream(ms)
ProfilePic.Image = img
con.Close()
End Using
End Using
End Using
End Using
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
NormalUpdate("Update Registration set MemberPicture = '" + fileContent.ToString + "' where MemberNo = '" + txtMemberNo.Text + "'")
End Sub
Please help me. Thanks.
Not sure if this is what you are looking for, but I use the following to get and set images from a database:
Public Function GetClientImage(ID As String) As Image
Dim ClientPicture As Image = Nothing
Dim DS As DataSet = Nothing
'Populate DS here
If (DS IsNot Nothing) AndAlso (DS.Tables.Count > 0) AndAlso (DS.Tables(0).Rows.Count > 0) Then
Dim DR As DataRow = DS.Tables(0).Rows(0)
Try
Dim Pic As Object = DR!Picture
If Pic IsNot DBNull.Value Then
Dim Buffer As Byte() = CType(DR!Picture, Byte())
If Buffer IsNot Nothing AndAlso (Buffer.Length > 0) Then
Using MS As New IO.MemoryStream(Buffer, 0, Buffer.Length)
MS.Write(Buffer, 0, Buffer.Length)
ClientPicture = Image.FromStream(MS, True)
End Using
End If
End If
Catch ex As Exception
MessageBox.Show("Error retrieving Image: " & ControlChars.NewLine & ControlChars.NewLine & ex.ToString, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End If
Return ClientPicture
End Function
and:
Public Function UpdateClientImage(ID As String, Pic As Image) As Integer
Dim Result As Integer = 0
If Client IsNot Nothing Then
Dim SQL As String = "UPDATE Clients SET Picture = #photo WHERE ID = '" & ID & "' ;"
Using SQLConn As New SqlClient.SqlConnection(ConnectionString)
Try
SQLConn.Open()
Using SQLCmd As New SqlClient.SqlCommand(SQL, SQLConn)
Dim PhotoParameter As New SqlClient.SqlParameter("#photo", SqlDbType.Image)
Dim MS As New IO.MemoryStream()
If Pic IsNot Nothing Then
Pic.Save(MS, Imaging.ImageFormat.Bmp)
End If
PhotoParameter.SqlValue = MS.GetBuffer
SQLCmd.Parameters.Add(PhotoParameter)
Result = SQLCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Dim Msg As String = "Unable to save Client's Picture"
If ex IsNot Nothing Then
Msg &= ":" & ControlChars.NewLine & ControlChars.NewLine & ex.ToString
End If
MessageBox.Show(Msg, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
If Not SQLConn.State = ConnectionState.Closed Then
SQLConn.Close()
End If
End Try
End Using
End If
Return Result
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles
Dim OpennFileDialog As OpenFileDialog
query = "update tblEmployeeSetup set dbImage = #dbImage where empy_id = '" + txtEmpId.Text + "' "
insertImage(query, "Data Saved...", lblSave, OpennFileDialog )
End Sub
Sub insertImage(ByVal query As String, ByVal message As String, ByVal lblSave As Label, ByVal a As OpenFileDialog)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim result As DialogResult = a.ShowDialog()
' a.FileName = My.Resources.DefultImage.ToString
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.Add(New SqlClient.SqlParameter("#dbimage", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
lblSave.Text = message
a.Dispose()
Catch ex As Exception
MessageBox.Show("Error" & ex.Message)
Finally
con.Close()
End Try
End Sub