PrintDocument failed to print the second time - vb.net

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.

Related

insert data row after row to datagridview upon pressed button? vb.net

How can I insert data row after row to DataGridView from database, from which the criteria is based on the name of a pressed button?
See my code below:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim selmenu As String = txtmenus.Text
Try
Dim btn1 As Button = CType(sender, Button)
Dim str As String = btn1.Text.Trim()
Dim str1 As Integer = Val(btn1.Name.Trim())
txtmenus.Text = Val(str1.ToString())
cmbGroup.Enabled = True
MessageBox.Show("ID: " & str1)
DataGridView1.Rows.Clear()
'If cmbBillType.Text = "Takeaway" Or cmbBillType.Text = "Express Billing" Or cmbBillType.Text = "Home Delivery" Then
con = New OleDbConnection(cs)
con.Open()
cmd = con.CreateCommand()
cmd.CommandText = "SELECT ItemID,Dishname, Rate from Dish,Category where Category.Categoryname=Dish.Category and ItemID=#d2"
cmd.Parameters.AddWithValue("#d2", Val(txtmenus.Text))
rdr = cmd.ExecuteReader()
If rdr.Read() Then
For Each r As DataGridViewRow In Me.DataGridView1.Rows
con = New OleDbConnection(cs)
con.Open()
cmd = con.CreateCommand()
cmd.CommandText = "SELECT ItemID,Dishname, Rate from Dish,Category where Category.Categoryname=Dish.Category and ItemID=#d2"
cmd.Parameters.AddWithValue("#d2", Val(txtmenus.Text))
If DataGridView1.Rows.Count > 0 Then
r.Cells(0).Value = rdr(0)
r.Cells(1).Value = rdr(1)
r.Cells(2).Value = rdr(2)
r.Cells(3).Value = 1
r.Cells(4).Value = r.Cells(2).Value * r.Cells(3).Value
Exit Sub
End If
Next
End If
DataGridView1.Rows.Add(rdr(0), rdr(1), rdr(2))
DataGridView1.Rows(0).Cells(3).Value = 1
DataGridView1.Rows(0).Cells(4).Value = DataGridView1.Rows(0).Cells(2).Value * DataGridView1.Rows(0).Cells(3).Value
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub

Updating Datagridview?

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)

Data not updated correctly

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()
.....

How to insert, edit, delete image in SQL using vb.net

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

VB: How to bind a DataTable to a DataGridView?

I know this is a basic question that has already been answered thousand times, but I can't make it work.
I am working in Visual Studio 2010 and have two forms in my Windows Application. In the first one (Main.vb), the user enters his inputs and the calculation takes place. In the second one (DataAnalysis.vb) the calculation results are displayed.
In Main.vb, I create the temp table that will contains all the intermediary calculation steps:
Dim tableTempJDL As DataTable = New DataTable("TempJDL")
Dim column As DataColumn
column = New DataColumn("ID", GetType(System.Int32))
tableTempJDL.Columns.Add(column)
column = New DataColumn("PthObjekt", GetType(System.Double))
tableTempJDL.Columns.Add(column)
'further columns are after created using the same method
Then, in DataAnalysis.vb, I try to display the DataTable tableTempJDL into the DataGridViewBerechnung:
Public bindingSourceBerechnung As New BindingSource()
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
But then I don't understand how to fill the DataGridView...
Simply, you can make your table as the datasource of bindingsource in following way:
Me.bindingSourceBerechnung .DataSource = tableTempJDL
Later on, you can bind above binding source in your datagridview in following way:
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
Public Class Form1
Dim CON As New SqlConnection
Dim CMD As New SqlCommand
Dim dt As New DataTable
Public Sub DbConnect()
If CON.State = ConnectionState.Open Then DbClose()
CON.ConnectionString = "Data Source = yourservername;Initial Catalog=your database name;Integrated Security=True"
CON.Open()
End Sub
Public Sub DbClose()
CON.Close()
CON.Dispose()
End Sub
Public Sub enabletext()
TextBox1.Enabled = True
End Sub
Public Sub CLEARFEILDS()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
ComboBox1.SelectedIndex = 0
DataGridView2.Rows.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Select()
TextBox4.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
'AUTOSEACH()
DbConnect()
Dim SELECTQUERY As String = "SELECT PROD_CODE FROM TBLPRODUCT"
Dim MYCOMMAND As New SqlCommand(SELECTQUERY, CON)
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
Prod_Code.Items.Clear()
While MYREADER.Read
Prod_Code.Items.Add(MYREADER("PROD_CODE"))
End While
DbClose()
End Sub
Public Function InvCodeGen(ByVal CurrCode As String) As String
Dim RightSix As String = Microsoft.VisualBasic.Right(Trim(CurrCode), 3)
Dim AddValue As Integer = Microsoft.VisualBasic.Val(RightSix) + 1
Dim RetValue As String
If Microsoft.VisualBasic.Len(AddValue.ToString) = 1 Then
RetValue = "00" + AddValue.ToString
ElseIf (Microsoft.VisualBasic.Len(AddValue.ToString) = 2) Then
RetValue = "000" + AddValue.ToString
Else
RetValue = AddValue.ToString
End If
Return RetValue
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateNewCode()
TextBox1.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
ComboBox1.Visible = True
AddCustomer()
'GridView2Load(GetDataGridView2())
End Sub
Private Sub CreateNewCode()
Dim CurrCode As String = ""
'Dim NewCode As String = "INV"
Dim NewCode As Integer
Dim mySelectQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myCommand As New SqlClient.SqlCommand(mySelectQuery, CON)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader
DbConnect()
myReader = myCommand.ExecuteReader()
Do While myReader.Read()
If IsDBNull(myReader("INVNO")) Then
myReader.Close()
Dim myNewYearQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myNewYearCommand As New SqlClient.SqlCommand(myNewYearQuery, CON)
myNewYearCommand.CommandType = CommandType.Text
Dim myNewYearReader As SqlClient.SqlDataReader
myNewYearReader = myNewYearCommand.ExecuteReader()
Do While myNewYearReader.Read()
CurrCode = Trim(myNewYearReader("INVNO").ToString)
Loop
myNewYearReader.Close()
Exit Do
Else
CurrCode = Trim(myReader("INVNO").ToString)
myReader.Close()
Exit Do
End If
Loop
DbClose()
NewCode = Trim(InvCodeGen(CurrCode))
TextBox1.Text = CInt(NewCode)
End Sub
Private Sub AddCustomer()
Dim dsCusCode As New DataSet
dsCusCode.Reset()
ComboBox1.Items.Clear()
Dim myCusCodeQuery As String = "SELECT CUST_CODE as Custcode FROM TBLCUSTOMER"
Dim daCusCode As New SqlClient.SqlDataAdapter(myCusCodeQuery, CON)
DbConnect()
daCusCode.Fill(dsCusCode, "TBLCUSTOMER")
DbClose()
Dim x As Integer
For x = 0 To dsCusCode.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dsCusCode.Tables(0).Rows(x).Item("Custcode").ToString)
'TextBox3.Text = dsCusCode.Tables(0).Rows(x).Item("custname").ToString
Next
ComboBox1.SelectedIndex = -1
x = Nothing
myCusCodeQuery = Nothing
dsCusCode.Dispose()
daCusCode.Dispose()
dsCusCode = Nothing
dsCusCode = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Code As String
Code = ComboBox1.Text
Dim dsCode As New DataSet
dsCode.Reset()
Dim myCodeQuery As String = "SELECT cust_name as custname, cust_add1 as custadd FROM TBLCUSTOMER where Cust_Code = '" & Code & "'"
Dim daCode As New SqlClient.SqlDataAdapter(myCodeQuery, CON)
DbConnect()
daCode.Fill(dsCode, "TBLCUSTOMER")
DbClose()
TextBox2.Text = dsCode.Tables(0).Rows(0).Item("custname").ToString
TextBox3.Text = dsCode.Tables(0).Rows(0).Item("custadd").ToString
myCodeQuery = Nothing
dsCode.Dispose()
daCode.Dispose()
dsCode = Nothing
dsCode = Nothing
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim MYQUERY As String = "SELECT PROD_DESC , PROD_PRICE FROM TBLPRODUCT WHERE PROD_CODE='" & DataGridView2.Rows(I).Cells(1).Value & "'"
Dim MYCOMMAND As New SqlCommand(MYQUERY, CON)
DbConnect()
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
If MYREADER.Read() Then
DataGridView2.Rows(I).Cells(2).Value = MYREADER("PROD_DESC")
DataGridView2.Rows(I).Cells(3).Value = MYREADER("PROD_PRICE")
End If
DbClose()
Next
End Sub
Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
DataGridView2.Rows(e.RowIndex).Cells(0).Value = CInt(e.RowIndex + 1)
End Sub
Private Sub DataGridView2_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellEndEdit
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim QTY As Double = DataGridView2.Rows(I).Cells(4).Value
Dim PRICE As Double = DataGridView2.Rows(I).Cells(3).Value
Dim AMOUNT As Double = QTY * PRICE
DataGridView2.Rows(I).Cells(5).Value = AMOUNT
Next
' SUM OF AMOUNT TOTAL
Dim COLSUM As Decimal = 0
For Each ROW As DataGridViewRow In DataGridView2.Rows
If Not IsDBNull(ROW.Cells(5).Value) Then
COLSUM += ROW.Cells(5).Value
End If
Next
TextBox4.Text = COLSUM
End Sub
'SAVE
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If MsgBox("Are you sure want to save this record?", vbYesNo + vbQuestion) = vbYes Then
updateinvheader()
updategridvalue()
CLEARFEILDS()
End If
End Sub
Private Sub updateinvheader()
Dim insertquery1 As String = "insert into TBLINV_HEADER(inv_no,inv_date,inv_cust) values(#inv_no,#inv_date,#inv_cust)"
Dim command As New SqlCommand(insertquery1, CON)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_date", DateTime.Now)
command.Parameters.AddWithValue("#inv_cust", ComboBox1.Text)
DbConnect()
command.ExecuteNonQuery()
DbClose()
End Sub
Private Sub updategridvalue()
Dim i As Integer
Dim insertquery2 As String = "insert into TBLINV_detail(inv_lno,inv_no,inv_prod,inv_qty,inv_Price) values(#inv_lno,#inv_no,#inv_prod,#inv_qty,#inv_Price)"
Dim command As New SqlCommand(insertquery2, CON)
For i = 0 To DataGridView2.RowCount - 1
If DataGridView2.Rows(i).Cells(1).Value = "" Then
GoTo 100
Else
command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).RowIndex + 1)
'command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_prod", DataGridView2.Rows(i).Cells(1).Value)
command.Parameters.AddWithValue("#inv_qty", DataGridView2.Rows(i).Cells(4).Value)
command.Parameters.AddWithValue("#inv_Price", DataGridView2.Rows(i).Cells(3).Value)
End If
DbConnect()
command.ExecuteNonQuery()
DbClose()
100: command.Parameters.Clear()
Next
MsgBox("data saved successfuly")
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
DataGridView1.Visible = True
TextBox5.Visible = True
ComboBox1.Visible = False
DbConnect()
Dim MYQUERY As String = "Select * FROM TBLCUSTOMER" &
" INNER Join TBLINV_HEADER ON TBLINV_HEADER.INV_CUST = TBLCUSTOMER.CUST_CODE" &
" WHERE TBLINV_HEADER.INV_NO ='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim DA As New SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
If DT.Rows.Count > 0 Then
MsgBox(DT.Rows(0)(1).ToString())
'ComboBox1.Text = DT.Rows(0)(1).ToString()
ComboBox1.Visible = False
TextBox5.Text = DT.Rows(0)(1).ToString()
TextBox2.Text = DT.Rows(0)(2).ToString()
TextBox3.Text = DT.Rows(0)(3).ToString()
End If
DbClose()
DataGridView1.DataSource = GETPRODUCTDETAILS()
End Sub
Private Function GETPRODUCTDETAILS() As DataTable
Dim PRODUCTDET As New DataTable
DbConnect()
Dim MYQUERY As String = " SELECT TBLINV_DETAIL.INV_LNO, TBLINV_DETAIL.INV_PROD, TBLPRODUCT.PROD_DESC, TBLINV_DETAIL.INV_PRICE, TBLINV_DETAIL.INV_QTY, (TBLINV_DETAIL.INV_QTY*TBLINV_DETAIL.INV_PRICE) AS AMOUNT FROM TBLINV_DETAIL " &
" INNER JOIN TBLPRODUCT On TBLPRODUCT.PROD_CODE = TBLINV_DETAIL.INV_PROD " &
" WHERE TBLINV_DETAIL.INV_NO='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim READER As SqlDataReader = CMD.ExecuteReader()
PRODUCTDET.Load(READER)
DbClose()
Return PRODUCTDET
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim DELETEQUERY As String = "DELETE FROM TBLINV_DETAIL WHERE TBLINV_DETAIL.INV_NO= '" & TextBox1.Text & "'"
Dim DELETEQUERY2 As String = "DELETE FROM TBLINV_HEADER WHERE TBLINV_HEADER.INV_NO= '" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(DELETEQUERY, CON)
Dim CMD2 As New SqlCommand(DELETEQUERY2, CON)
DbConnect()
CMD.ExecuteNonQuery()
CMD2.ExecuteNonQuery()
DbClose()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
DataGridView1.DataSource = Nothing
MsgBox("DATA DELETED SUCCESSFULLY")
End Sub
End Class