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 have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class search
Dim conn As New SqlConnection
Dim da As New SqlDataAdapter
Dim strcon As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Application\Abhi\Software\Software\Vansh.mdf;Integrated Security=True;User Instance=True"
Private Sub search_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Application\Abhi\Software\Software\Vansh.mdf;Integrated Security=True;User Instance=True"
conn = New SqlConnection(strcon)
conn.Open()
loaddata()
' txtsearch.Enabled = False
' txtsearch.Text = "Student Id is auto number"
End Sub
Public Sub loaddata()
conn = New SqlConnection(strcon)
conn.Open()
Dim str As String = "Select * From Payment "
da = New SqlDataAdapter(str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
For Each txt In {txtmo, txtsearch}
txt.Clear()
Next
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs)
End Sub
Private Sub btnhome_Click(sender As System.Object, e As System.EventArgs) Handles btnhome.Click
Me.Hide()
Dim rd As New Home_Page
rd.Show()
End Sub
Private Sub txtsearch_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtsearch.TextChanged
Try
conn = New SqlConnection(strcon)
conn.Open()
If txtsearch.Text = " " Then
loaddata()
Else
conn = New SqlConnection(strcon)
conn.Open()
Dim Str As String = "Select Date, Name, Amount from Payment where Name like '" + txtsearch.Text + "%' "
da = New SqlDataAdapter(Str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub txtmo_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtmo.TextChanged
Try
conn = New SqlConnection(strcon)
conn.Open()
If txtsearch.Text = " " Then
loaddata()
Else
conn = New SqlConnection(strcon)
conn.Open()
Dim Str As String = "Select Date, Name, Amount from Payment where Date like '" + txtmo.Text + "%' "
da = New SqlDataAdapter(Str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker1.ValueChanged
Try
conn = New SqlConnection(strcon)
conn.Open()
If txtsearch.Text = " " Then
loaddata()
Else
conn = New SqlConnection(strcon)
conn.Open()
Dim Str As String = "Select Date, Name, Amount from Payment where Date like '" + DateTimePicker1.Text + "%' "
da = New SqlDataAdapter(Str, conn)
Dim ds As New DataSet
da.Fill(ds, "Payment")
DataGridView1.DataSource = ds.Tables("Payment")
da.Dispose()
conn.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView2_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
End Sub
End Class
This are my code, It worked perfectly except for ONE. I can't update:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim Cmd As SqlCommand
Dim Query As String
Sub disk()
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "UPDATE AdminESP SET Benefactor='" & CmbBenefactor.Text & "' WHERE ExternalSP='" & CmbExternalSP.Text & "'"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
con.Close()
End Sub
Sub dis()
CmbExternalSP.Items.Clear()
CmbBenefactor.Items.Clear()
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "select * from [AJLMNewProjectDatabase].[dbo].[AdminESP]"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
While READER.Read
Dim ESP = READER.GetString(1)
Dim Ben = READER.GetString(2)
CmbExternalSP.Items.Add(ESP)
CmbBenefactor.Items.Add(Ben)
End While
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "select * from AdminESP"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
While READER.Read
Dim ESP = READER.GetString(1)
Dim Ben = READER.GetString(2)
CmbExternalSP.Items.Add(ESP)
CmbBenefactor.Items.Add(Ben)
End While
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub CmbExternalSP_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbExternalSP.SelectedIndexChanged
CmbBenefactor.SelectedIndex = CmbExternalSP.SelectedIndex
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
con = New SqlConnection("Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;")
con.Open()
Cmd = con.CreateCommand
Cmd.CommandText = String.Format("INSERT INTO AdminESP(ExternalSP, Benefactor) " &
"VALUES('{0}', '{1}')",
CmbExternalSP.Text,
CmbBenefactor.Text) ' To Save data to ExternalSP DataTable
Dim rowsAffected As Integer = Cmd.ExecuteNonQuery()
If rowsAffected > 0 Then
MsgBox("Program Added!")
Else
MsgBox("Failed to Add")
End If
CmbExternalSP.Text = ""
CmbBenefactor.Text = ""
con.Close()
End Sub
Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
CmbExternalSP.DropDownStyle = ComboBoxStyle.DropDown
CmbBenefactor.DropDownStyle = ComboBoxStyle.DropDown
CmbExternalSP.Text = ""
CmbBenefactor.Text = ""
End Sub
Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "DELETE FROM AdminESP WHERE ExternalSP='" + CmbExternalSP.Text + "'"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
If MessageBox.Show("You are about to remove a Program, Please confirm your Action.", "DELETE", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.OK Then
MsgBox("Program Removed")
End If
CmbExternalSP.Text = ""
CmbBenefactor.Text = ""
CmbExternalSP.DropDownStyle = ComboBoxStyle.DropDownList
CmbBenefactor.DropDownStyle = ComboBoxStyle.DropDownList
Call dis()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
con.Close()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
con = New SqlConnection
con.ConnectionString = "Server=Jansen\SQLEXPRESS;Database=AJLMNewProjectDatabase;Trusted_Connection=True;"
Try
con.Open()
Dim READER As SqlDataReader
Query = "UPDATE AdminESP SET ExternalSP='" & CmbExternalSP.Text & "' WHERE Benefactor='" & CmbBenefactor.Text & "'"
Cmd = New SqlCommand(Query, con)
READER = Cmd.ExecuteReader()
MessageBox.Show("Program Updated.")
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
con.Close()
End Sub
Private Sub BtnR_Click(sender As Object, e As EventArgs) Handles BtnR.Click
Call dis()
End Sub
Private Sub CmbBenefactor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbBenefactor.SelectedIndexChanged
CmbExternalSP.SelectedIndex = CmbBenefactor.SelectedIndex
End Sub
End Class
Now my problem is, When I click UPDATE button, only one column which is under combobox 1 updates; the other combobox doesn't change at all.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
i have this problem"error coding (Object reference not set to an instance of an object)" please help me and this my full coding.
Imports MySql.Data.MySqlClient
Public Class Form1
Dim MysqlConn As MySqlConnection
Dim Command As MySqlCommand
Dim Reader As MySqlDataReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Sda As New MySqlDataAdapter
Try
If Button1.BackColor = Color.Lime Then
Me.Button1.BackColor = Color.Lime
End If
MysqlConn.Open()
Dim query As String
query = "select * from info.penjara"
query = "update penjara.info set keadaan =1 where no =1 "
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader()
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
Dim spath As String
Dim mysound As Media.SoundPlayer
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
If Button1.BackColor = Color.Lime Then
mysound.PlayLooping()
End If
Form2.Show()
Me.Hide()
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Sda As New MySqlDataAdapter
Try
If Button2.BackColor = Color.Lime Then
Me.Button2.BackColor = Color.Lime
End If
MysqlConn.Open()
Dim query As String
query = "select * from info.penjara"
query = "update penjara.info set keadaan =1 where no =2 "
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader()
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
Dim spath As String
Dim mysound As Media.SoundPlayer
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
If Button2.BackColor = Color.Lime Then
mysound.PlayLooping()
End If
Form3.Show()
Me.Hide()
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Sda As New MySqlDataAdapter
Try
If Button3.BackColor = Color.Lime Then
Me.Button3.BackColor = Color.Lime
End If
MysqlConn.Open()
Dim query As String
query = "select * from info.penjara"
query = "update penjara.info set keadaan =1 where no =3 "
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader()
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
Dim spath As String
Dim mysound As Media.SoundPlayer
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
If Button3.BackColor = Color.Lime Then
mysound.PlayLooping()
End If
Form4.Show()
Me.Hide()
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Sda As New MySqlDataAdapter
Try
If Button4.BackColor = Color.Lime Then
Me.Button4.BackColor = Color.Lime
End If
MysqlConn.Open()
Dim query As String
query = "select * from info.penjara"
query = "update penjara.info set keadaan =1 where no =4 "
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader()
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
Dim spath As String
Dim mysound As Media.SoundPlayer
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
If Button4.BackColor = Color.Lime Then
mysound.PlayLooping()
End If
Form5.Show()
Me.Hide()
End Try
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Sda As New MySqlDataAdapter
Try
If Button5.BackColor = Color.Lime Then
Me.Button5.BackColor = Color.Lime
End If
MysqlConn.Open()
Dim query As String
query = "select * from info.penjara"
query = "update penjara.info set keadaan =1 where no =5 "
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader()
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
Dim spath As String
Dim mysound As Media.SoundPlayer
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
If Button5.BackColor = Color.Lime Then
mysound.PlayLooping()
End If
Form6.Show()
Me.Hide()
End Try
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Reader As MySqlDataReader
MysqlConn.Open()
Dim query As String
Dim spath As String
Dim count As Integer = 0
Dim mysound As Media.SoundPlayer
Dim cmd As MySqlCommand
Dim rdr As MySqlDataReader
query = "Select * from penjara.info"
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader
While Reader.Read
Try
Reader.Close()
count = count + 1
query = "Select penjara.info where no = '" & count & "'"
cmd = New MySqlCommand(query, MysqlConn)
rdr = cmd.ExecuteReader
Catch ex As Exception
If (rdr.GetInt32("keadaan") = 1) & (rdr.GetInt32("no") = count) Then
Form2.Show()
Me.Hide()
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
mysound.PlayLooping()
ElseIf (rdr.GetInt32("keadaan") = 1) & (rdr.GetInt32("no") = count) Then
Form3.Show()
Me.Hide()
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
mysound.PlayLooping()
ElseIf (rdr.GetInt32("keadaan") = 1) & (rdr.GetInt32("no") = count) Then
Form4.Show()
Me.Hide()
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
mysound.PlayLooping()
ElseIf (rdr.GetInt32("keadaan") = 1) & (rdr.GetInt32("no") = count) Then
Form5.Show()
Me.Hide()
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
mysound.PlayLooping()
ElseIf (rdr.GetInt32("keadaan") = 1) & (rdr.GetInt32("no") = count) Then
Form5.Show()
Me.Hide()
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
mysound.PlayLooping()
End If
End Try
End While
End Sub
End Class
Since the error-causing line is in a Catch block and rdr is only set in the accompanying Try, there's no guarantee that rdr is ever initialized. Since the data schema is not using English (I think?), I'm not really sure what you're trying to accomplish with the handler. I recommend doing an If rdr Is Nothing and doing a separate error type for that before going into what you currently have in the Catch block.
And, as people pointed out in the comments, use the And operator (or AndAlso to replicate C# behavior) instead of &, which is the string concatenator in VB.NET.
Look what you have going on here:
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=;database=penjara"
Dim Reader As MySqlDataReader
MysqlConn.Open()
Dim query As String
Dim spath As String
Dim count As Integer = 0
Dim mysound As Media.SoundPlayer
Dim cmd As MySqlCommand
Dim rdr As MySqlDataReader
query = "Select * from penjara.info"
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader
While Reader.Read
Try
Reader.Close()
count = count + 1
query = "Select penjara.info where no = '" & count & "'"
cmd = New MySqlCommand(query, MysqlConn)
rdr = cmd.ExecuteReader
You've got 2 readers: Dim Reader As MySqlDataReader and Dim rdr As MySqlDataReader.
You do Reader = Command.ExecuteReader and a While Reader.Read and then immediately close it via Reader.Close(). That's problem 1. Problem 1a is that you are even looping through that first Reader. Why? You aren't doing anything with it?
Problem 2 is that your second Reader you do rdr = cmd.ExecuteReader yet you don't do anything with it. It seems to me that your If statement wasn't supposed to be inside of the Catch but underneath the rdr = cmd.ExecuteReader. Therefore, move your Catch down after the If statement where you are using the rdr object.
Problem 3 is your & inside the If statement. Those need to be changed to AndAlso.
Here is how I tried to salvage things:
Try
count = count + 1
query = "Select penjara.info where no = '" & count & "'"
cmd = New MySqlCommand(query, MysqlConn)
rdr = cmd.ExecuteReader
While rdr.Read
Dim keadaan = rdr.GetInt32("keadaan")
Dim no = rdr.GetInt32("no")
If keadaan = 1 AndAlso no = count Then
Form2.Show()
Me.Hide()
spath = "C:\Users\User\Music\emergency003.wav"
mysound = New Media.SoundPlayer(spath)
mysound.PlayLooping()
ElseIf 'insert all the other conditions here ...
End If
End While
Catch ex As Exception
'TODO: Handle exception.
End Try