Adding images to Access Database Vb.net - Insert into syntax error - sql

I'm quite new to Visual Basic. I'm developing a simple Student Registration System that has a profile of Students with a photo in it. I managed to get the image addition code online and I tried to figure it out and use it for my program. All is set except the sql insert statement that will insert the photo into the "Image" field of the "Students" table of my database. When I click the save button, I keep getting Insert into syntax error but I can't seem to figure out exactly what the error in the sql statement is. I would appreciate it if I can get help with it. This is the whole code for the profile but I have put a comment where the sql statement is so you can go straight there. Thanks and Thanks again
Imports System.IO
Imports System.Data.OleDb
Public Class Profile
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim conString As String
Dim inc As Integer
Dim maxrows As Integer
Dim dsNewRow As DataRow
Dim SID As String
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles txtNationality.SelectedIndexChanged
End Sub
Private Sub GroupBox1_Enter(sender As Object, e As EventArgs) Handles GroupBox1.Enter
End Sub
Private Sub ProfileRecords()
txtFirstName.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(1)
txtMiddleName.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(2)
txtLastName.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(3)
txtGender.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(4)
txtNationality.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(5)
txtLevel.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(6)
txtFaculty.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(7)
txtProgramme.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(8)
txtAcademicPeriod.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(9)
txtDateRegistered.Text = ds.Tables("StudentRegSYS").Rows(inc).Item(10)
maxrows = ds.Tables("StudentRegSYS").Rows.Count
txtFirstName.ReadOnly = True
txtMiddleName.ReadOnly = True
txtLastName.ReadOnly = True
txtGender.Enabled = False
txtFaculty.Enabled = False
txtLevel.ReadOnly = True
txtNationality.Enabled = False
txtProgramme.Enabled = False
txtAcademicPeriod.ReadOnly = True
txtDateRegistered.ReadOnly = True
End Sub
Private Sub Profile_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SID = Login.txtstudentid.Text
btneditcancel.Visible = False
btneditsave.Visible = False
btnbrowseimage.Visible = False
txtimagepath.Visible = False
Try
conString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Yaw Biney\Documents\Visual Studio 2015\Projects\Student Registration System\Student Registration System\StudentRegSYS.accdb"
con = New OleDbConnection(conString)
con.Open()
sql = "select * from Students Where SID='" + SID + "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "StudentRegSYS")
con.Close()
Catch EXP As Exception
MessageBox.Show(EXP.ToString)
End Try
con.Open()
ProfileRecords()
txtNationality.Items.Add("Ghanaian")
txtNationality.Items.Add("Togolese")
txtNationality.Items.Add("Gabonese")
txtNationality.Items.Add("Ivorian")
txtNationality.Items.Add("Burkinabe")
txtNationality.Items.Add("Nigerian")
txtNationality.Items.Add("Beninois")
txtFaculty.Items.Add("Informatics")
txtFaculty.Items.Add("Engineering")
txtFaculty.Items.Add("Business")
txtProgramme.Items.Add("Bsc. Information Technology")
txtProgramme.Items.Add("Bsc. Telecom Engineering")
txtProgramme.Items.Add("Bsc. Computer Engineering")
txtProgramme.Items.Add("BA. Business Administration")
txtProgramme.Items.Add("Diploma in Information Technology")
txtProgramme.Items.Add("Diploma in Business Studies")
txtwelcomemsg.Text = "Welcome " & txtLastName.Text & ", " & txtFirstName.Text & " " & txtMiddleName.Text
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles txtMiddleName.TextChanged
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
btneditcancel.Visible = True
btneditsave.Visible = True
btnbrowseimage.Visible = True
txtimagepath.Visible = True
txtFirstName.ReadOnly = False
txtMiddleName.ReadOnly = False
txtLastName.ReadOnly = False
txtGender.Enabled = True
txtFaculty.Enabled = True
txtLevel.ReadOnly = False
txtNationality.Enabled = True
txtProgramme.Enabled = True
txtAcademicPeriod.ReadOnly = False
txtDateRegistered.ReadOnly = False
End Sub
Private Sub btneditcancel_Click(sender As Object, e As EventArgs) Handles btneditcancel.Click
btneditcancel.Visible = False
btneditsave.Visible = False
btnbrowseimage.Visible = False
txtimagepath.Visible = False
txtFirstName.ReadOnly = True
txtMiddleName.ReadOnly = True
txtLastName.ReadOnly = True
txtGender.Enabled = False
txtFaculty.Enabled = False
txtLevel.ReadOnly = True
txtNationality.Enabled = False
txtProgramme.Enabled = False
txtAcademicPeriod.ReadOnly = True
txtDateRegistered.ReadOnly = True
End Sub
Private Sub btneditsave_Click(sender As Object, e As EventArgs) Handles btneditsave.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Try
ds.Tables("StudentRegSYS").Rows(inc).Item(1) = txtFirstName.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(2) = txtMiddleName.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(3) = txtLastName.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(4) = txtGender.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(5) = txtNationality.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(6) = txtLevel.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(7) = txtFaculty.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(8) = txtProgramme.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(9) = txtAcademicPeriod.Text
ds.Tables("StudentRegSYS").Rows(inc).Item(10) = txtDateRegistered.Text
da.Update(ds, "StudentRegSYS")
MessageBox.Show("Profile updated successfully")
Catch ex As Exception
MessageBox.Show("Error: " & ex.ToString())
End Try
'Error seems to be from here on going'
Try
Dim MemStream As New MemoryStream
Dim DataPic_Update As Byte()
Me.picboxprofilepic.Image.Save(MemStream, Imaging.ImageFormat.Jpeg)
DataPic_Update = MemStream.GetBuffer()
MemStream.Read(DataPic_Update, 0, MemStream.Length)
Dim cmd As OleDbCommand = New OleDbCommand("INSERT INTO Students (Image) VALUES(#Image)", con)
Dim photo As OleDbParameter = New OleDbParameter("#Image", SqlDbType.Image)
photo.Value = DataPic_Update
cmd.Parameters.Add(photo)
cmd.ExecuteNonQuery()
MessageBox.Show("Record Is Added")
Catch ex As Exception
MessageBox.Show("Error: " & ex.ToString())
End Try
btneditcancel.Visible = False
btneditsave.Visible = False
btnbrowseimage.Visible = False
txtimagepath.Visible = False
txtFirstName.ReadOnly = True
txtMiddleName.ReadOnly = True
txtLastName.ReadOnly = True
txtGender.Enabled = False
txtFaculty.Enabled = False
txtLevel.ReadOnly = True
txtNationality.Enabled = False
txtProgramme.Enabled = False
txtAcademicPeriod.ReadOnly = True
txtDateRegistered.ReadOnly = True
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Change_Password.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnbrowseimage.Click
OpenFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*"
If OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Me.picboxprofilepic.Image = System.Drawing.Image.FromFile(OpenFileDialog1.FileName)
txtimagepath.Text = OpenFileDialog1.FileName
End If
End Sub
End Class

Related

show groupboxes depending on selection in listbox access database vb.net

I have an access databasetable with addresses and a table with addresstypes.
When i add a new relation there's different groupboxes with additional information that should be displayed according to the addresstype.
For example: a patient has only basic address info.
A doctor needs a reference number too, so if i click on relation type "doctor" the address groupbox should appear but also the groupbox with doctor reference textbox.
An instance should also get the instance groupbox + address groupbox etc etc.
Addresses can also be "multiple types" so if an address is A: a doctor, and B an instance, both boxes should appear.
My current code looks like this:
Public Class NewRelationForm
'groupboxen disablen on load
Me.grpKiesUwRelatietype.Visible = True
Me.grpBasisData.Visible = False
Me.grpDataBI.Visible = False
Me.grpFoto_Nota.Visible = False
Me.grpHuisartsData.Visible = False
Me.grpPartijData.Visible = False
Me.grpVerwijzerdata.Visible = False
End Sub
'KNOPPEN en Functies!
Private Sub NewRelationForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_TypeTableAdapter1.Fill(Me.PatientenDatabaseDataSetX1.tbl_Type)
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX1.tbl_OnderzoeksTypes)
Me.Tbl_RelatiesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Relaties)
End Sub
Private Sub btnAddRelation_Click(sender As Object, e As EventArgs) Handles btnAddRelation.Click
FormMakeRelationType.Show()
End Sub
Private Sub lboxRelatieTypes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lboxRelatieTypes.SelectedIndexChanged
End Sub
'Private Sub lboxRelatieTypes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lboxRelatieTypes.SelectedIndexChanged
''If ComboBox1.SelectedIndex = 1 Then
'' grpBasisData.Visible = True
'' grpFoto_Nota.Visible = True
'' grpFoto_Nota.Location = New Point(720, 120)
''End If
'End Sub
End Class
I could really use a pointer in how to do this, i've tried if else, i've tried select case, but i can't find "the right way".
I'm a beginner
edit1: This is a pic from the winform: https://imgur.com/a/80pKnjR
and this is the access db (names in the db are changed for privacy purposes
https://www.dropbox.com/sh/4gudk8lwxtjahiq/AACz69ocFWIlU7hiTlQxbviLa?dl=0
I found it...
based on an article in stackoverflow: How to show hidden text boxes when items are selected in a combo box
If someone knows how to make this piece of code "easier to handle" or "more compact" i'm very open to ideas.
Also: i can only select one , the rest of the groupboxes dissappear , so it needs some finetuning but i'm 90% there!
Private Sub lboxRelatieTypes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lboxRelatieTypes.SelectedIndexChanged
If lboxRelatieTypes.Text.Trim.Contains("Patiƫnt") = True Then
Me.grpBasisData.Visible = True
Me.grpDataBI.Visible = False
Me.grpFoto_Nota.Visible = True
Me.grpHuisartsData.Visible = False
Me.grpPartijData.Visible = False
Me.grpVerwijzerdata.Visible = False
ElseIf lboxRelatieTypes.Text.Trim.Contains("Verwijzer") = True Then
Me.grpBasisData.Visible = True
Me.grpDataBI.Visible = False
Me.grpFoto_Nota.Visible = True
Me.grpHuisartsData.Visible = False
Me.grpPartijData.Visible = False
Me.grpVerwijzerdata.Visible = True
ElseIf lboxRelatieTypes.Text.Trim.Contains("Betalende Instantie") = True Then
Me.grpBasisData.Visible = True
Me.grpDataBI.Visible = True
Me.grpFoto_Nota.Visible = True
Me.grpHuisartsData.Visible = False
Me.grpPartijData.Visible = True
Me.grpVerwijzerdata.Visible = False
ElseIf lboxRelatieTypes.Text.Trim.Contains("Huisarts") = True Then
Me.grpBasisData.Visible = True
Me.grpDataBI.Visible = False
Me.grpFoto_Nota.Visible = True
Me.grpHuisartsData.Visible = True
Me.grpPartijData.Visible = False
Me.grpVerwijzerdata.Visible = False
ElseIf lboxRelatieTypes.Text.Trim.Contains("Huisarts" & "Betalende Instantie") = True Then
Me.grpBasisData.Visible = True
Me.grpDataBI.Visible = True
Me.grpFoto_Nota.Visible = True
Me.grpHuisartsData.Visible = True
Me.grpPartijData.Visible = False
Me.grpVerwijzerdata.Visible = False
End If
'Dim curitem As String = lboxRelatieTypes.SelectedItems.ToString()
'Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
'con.Open()
'Dim sql As String = String.Format("select * from tbl_Relaties where Rel_Type='{0}'", curitem)
'Dim command As New OleDbCommand(sql, con)
'Dim reader As OleDbDataReader = command.ExecuteReader()
'If curitem.Contains "Huisarts" Then
' End If
'con.Close()
I make a code example, which show the textbox in the groupbox based on the listbox.
Form_Load event:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\PatientenDatabase.mdb")
con.Open()
Dim sql As String = "select Type_Naam from tbl_type"
Dim command As New OleDbCommand(sql, con)
Dim reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
ListBox1.Items.Add(reader.GetString(0))
End While
con.Close()
End Sub
Listboxindexchanged event:
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As String = ListBox1.SelectedItem.ToString()
Dim con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\PatientenDatabase.mdb")
con.Open()
Dim sql As String = String.Format("select * from tbl_Relaties where Rel_Type='{0}'", curItem)
Dim command As New OleDbCommand(sql, con)
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
While reader.Read()
txtID.Text = reader.GetValue(0).ToString()
txtType.Text = reader.GetValue(1).ToString()
txtName.Text = reader.GetValue(2).ToString()
txtVoo.Text = reader.GetValue(3).ToString()
txtAdress.Text = reader.GetValue(4).ToString()
End While
Else
txtID.Text = String.Empty
txtType.Text = String.Empty
txtName.Text = String.Empty
txtVoo.Text = String.Empty
txtAdress.Text = String.Empty
End If
con.Close()
End Sub
Final result:
Besides, I only make a few column code and you can follow the above code to complete the rest of the code.

Update Database and datagridview from textboxes

I have an application with a datagridview on the bottom half of the page and textboxes, combo-boxes, buttons, etc... on the top half.
When the user changes the highlighted row in the grid then it displays all of the information for that row in the objects on the top half.
If user wants to change the data in a row then he clicks an edit button which enables the textboxes etc... and allows the user to edit the data.
(All of the above works fine).
When he wants to save the changes then he clicks the save button.
This should update the datasource to the grid and show the changes in the grid.
However, I have been unable to get it do this.
Any Help appreciated.
Code below:
Imports System.Data.SqlClient
Public Class frmEmployeeInformation
Public SQL As New SQLControl()
Dim strEditType As String
Private Sub frmEmployeeInformation_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadGrid()
End Sub
Public Sub LoadGrid(Optional query As String = "")
If query = "" Then
SQL.ExecuteQuery("Select * from EmployeeInformation;")
Else
SQL.ExecuteQuery(query)
End If
If SQL.HasException(True) Then Exit Sub
dgvEmployeeInformation.DataSource = SQL.DBDS.Tables(0)
dgvEmployeeInformation.Rows(0).Selected = True
SQL.DBDA.UpdateCommand = New SqlClient.SqlCommandBuilder(SQL.DBDA).GetUpdateCommand
End Sub
Private Sub DisplayValues()
If dgvEmployeeInformation.RowCount > 2 Then
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value <> Nothing Then
txtFirstName.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value.ToString 'EmployeeInformation.FirstName
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value <> Nothing Then
txtLastName.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value.ToString 'EmployeeInformation.LastName
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value IsNot Nothing Then
txtSSN.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value.ToString 'EmployeeInformation.SSN
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value <> Nothing Then
txtEmployeeID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value.ToString 'EmployeeInformation.EmployeeInformationID
End If
'If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value <> Nothing Then
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'End If
'If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value <> Nothing Then
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
'End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value <> Nothing Then
cboDefaultLocation.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value.ToString 'EmployeeInformation.DefaultLocation
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value <> Nothing Then
txtTableID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value.ToString 'EmployeeInformation.TableID
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value <> Nothing Then
chkbxActive.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value.ToString 'EmployeeInformation.EmployeeActive
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value <> Nothing Then
chkbxPrimaryFile.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value.ToString 'EmployeeInformation.PrimaryFile
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value <> Nothing Then
chkbxUnallocatedTime.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value.ToString 'EmployeeInformation.UnallocatedTime
End If
End If
End Sub
Private Sub ChangeButtons()
btnClose.Enabled = Not btnClose.Enabled
btnSave.Enabled = Not btnSave.Enabled
btnClear.Enabled = Not btnClear.Enabled
btnFind.Enabled = Not btnFind.Enabled
btnCancel.Enabled = Not btnCancel.Enabled
btnEdit.Enabled = Not btnEdit.Enabled
btnAdd.Enabled = Not btnAdd.Enabled
btnCopy.Enabled = Not btnCopy.Enabled
End Sub
Private Sub ChangeFields()
chkbxActive.Enabled = Not chkbxActive.Enabled
chkbxPrimaryFile.Enabled = Not chkbxPrimaryFile.Enabled
chkbxUnallocatedTime.Enabled = Not chkbxUnallocatedTime.Enabled
txtTableID.Enabled = Not txtTableID.Enabled
txtADPID.Enabled = Not txtADPID.Enabled
cboVP.Enabled = Not cboVP.Enabled
cboDefaultLocation.Enabled = Not cboDefaultLocation.Enabled
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
If txtEmployeeID.Text <> "" Then
SQL.AddParam("#EmployeeInformationID", txtEmployeeID.Text)
LoadGrid("select * from EmployeeInformation where EmployeeInformationID = #EmployeeInformationID;")
ElseIf txtSSN.Text <> "" Then
SQL.AddParam("#SSN", txtSSN.Text)
LoadGrid("select * from EmployeeInformation where SSN = #SSN;")
ElseIf txtFirstName.Text <> "" And txtLastName.Text <> "" Then
SQL.AddParam("#FirstName", txtFirstName.Text)
SQL.AddParam("#LastName", txtLastName.Text)
LoadGrid("select * from EmployeeInformation where FirstName = #FirstName and LastName = #LastName;")
Else
LoadGrid("Select * from EmployeeInformation;")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtFirstName.Text = ""
txtLastName.Text = ""
txtSSN.Text = ""
txtEmployeeID.Text = ""
txtADPID.Text = ""
cboVP.Text = ""
cboDefaultLocation.Text = ""
txtTableID.Text = ""
chkbxActive.Checked = "False"
chkbxPrimaryFile.Checked = "False"
chkbxUnallocatedTime.Checked = "False"
End Sub
Private Sub dgvEmployeeInformation_DoubleClick(sender As Object, e As EventArgs) Handles dgvEmployeeInformation.DoubleClick
DisplayValues()
ChangeFields()
ChangeButtons()
End Sub
Private Sub dgvEmployeeInformation_SelectionChanged(sender As Object, e As EventArgs) Handles dgvEmployeeInformation.SelectionChanged
DisplayValues()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If strEditType = "Edit" Then
' The code below updates the grid but the changes are not saved to the database. Probably not the way to go
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value = txtFirstName.Text 'EmployeeInformation.FirstName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value = txtLastName.Text 'EmployeeInformation.LastName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value = txtSSN.Text 'EmployeeInformation.SSN
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value = txtEmployeeID.Text 'EmployeeInformation.EmployeeInformationID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value = cboDefaultLocation.Text 'EmployeeInformation.DefaultLocation
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value = txtTableID.Text 'EmployeeInformation.TableID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value = chkbxActive.Checked 'EmployeeInformation.EmployeeActive
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value = chkbxPrimaryFile.Checked 'EmployeeInformation.PrimaryFile
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value = chkbxUnallocatedTime.Checked 'EmployeeInformation.UnallocatedTime
' The code above updates the grid but the changes are not saved to the database.
dgvEmployeeInformation.EndEdit()
SQL.DBDS.Tables(0).AcceptChanges()
SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
ChangeFields()
ChangeButtons()
strEditType = ""
'LoadGrid()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
ChangeFields()
ChangeButtons()
strEditType = ""
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
dgvEmployeeInformation_DoubleClick(Nothing, EventArgs.Empty)
strEditType = "Edit"
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
btnClear_Click(Nothing, EventArgs.Empty)
txtFirstName.Focus()
strEditType = "Add"
ChangeFields()
ChangeButtons()
End Sub
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
cboDefaultLocation.Focus()
strEditType = "Copy"
ChangeFields()
ChangeButtons()
End Sub
End Class
TRY ANOTHER WAY!!
I suggest you, instead of doing this:
If strEditType = "Edit" Then
' The code below updates the grid but the changes are not saved to the database. Probably not the way to go
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value = txtFirstName.Text 'EmployeeInformation.FirstName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value = txtLastName.Text 'EmployeeInformation.LastName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value = txtSSN.Text 'EmployeeInformation.SSN
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value = txtEmployeeID.Text 'EmployeeInformation.EmployeeInformationID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value = cboDefaultLocation.Text 'EmployeeInformation.DefaultLocation
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value = txtTableID.Text 'EmployeeInformation.TableID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value = chkbxActive.Checked 'EmployeeInformation.EmployeeActive
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value = chkbxPrimaryFile.Checked 'EmployeeInformation.PrimaryFile
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value = chkbxUnallocatedTime.Checked 'EmployeeInformation.UnallocatedTime
' The code above updates the grid but the changes are not saved to the database.
dgvEmployeeInformation.EndEdit()
SQL.DBDS.Tables(0).AcceptChanges()
SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
to first update your DB and than to update the datagrid from your DB.
Something like
Sql = "update TABLE_Name set FirstName = #fName" 'write all your query'
myCmd = New SqlCommand(Sql, myConn)
myCmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = txtFirstName.Text
myCmd.ExecuteNonQuery()
MsgBox("Update complete.")
myConn.Close()
And than you can update your datagrid! I'm always used to connect my DataGrid to my SQL table, so the code will be:
Public Sub Updating()
Me.Table_NameTableAdapter.Fill(Me.DB_NameDataSet1.Table_Name)
End Sub
Got it to work:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim dbconn As New SqlConnection("server=192.168.50.205;Database=SEMHC_Admin2018;trusted_Connection=True;")
Dim mycmd As SqlCommand
Dim mySQL As String
dbconn.Open()
If strEditType = "Add" Or strEditType = "Copy" Then
End If
If strEditType = "Edit" Then
mySQL = "update employeeInformation
set FirstName = #firstName,
LastName = #LastName,
SSN = #SSN,
EmployeeInformationID = #EmployeeInformationID,
Default_LocationID = #Default_LocationID,
EmployeeActive = #chkbxActive,
PrimaryFile = #chkbxPrimaryFile,
UnallocatedTime = #chkbxUnallocatedTime
from employeeInformation
WHERE SystemTableID = #SystemTableID
" 'write query'
mycmd = New SqlCommand(mySQL, dbconn)
mycmd.Parameters.Add("#SystemTableID", SqlDbType.VarChar).Value = txtTableID.Text
mycmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text
mycmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text
mycmd.Parameters.Add("#SSN", SqlDbType.VarChar).Value = txtSSN.Text
mycmd.Parameters.Add("#EmployeeInformationID", SqlDbType.VarChar).Value = txtEmployeeID.Text
mycmd.Parameters.Add("#Default_LocationID", SqlDbType.VarChar).Value = cboDefaultLocation.Text
mycmd.Parameters.Add("#chkbxActive", SqlDbType.VarChar).Value = chkbxActive.Checked
mycmd.Parameters.Add("#chkbxPrimaryFile", SqlDbType.VarChar).Value = chkbxPrimaryFile.Checked
mycmd.Parameters.Add("#chkbxUnallocatedTime", SqlDbType.VarChar).Value = chkbxUnallocatedTime.Checked
mycmd.ExecuteNonQuery()
'MsgBox("Update complete.")
dbconn.Close()
'SQL.DBDS.Tables(0).AcceptChanges()
'SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
ChangeFields()
ChangeButtons()
strEditType = ""
LoadGrid()
End Sub

WebBrowser and BackgroundWorker VB

Can a WebBrowser.DocumentCompleted event executes the BackgroundWorker.RunWorkerAsync() correctly? Because my program doesn't seem to execute the codes under BackgroundWorker.
Code:
Dim Status As String = ""
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If Status = "Enabled" Or Status = "Disabled" Then
Else
Status = WebBrowser1.Document.GetElementById(Account & "Flag").InnerText.ToString
If Status = "Enabled" Then
BackgroundWorker1.RunWorkerAsync()
ElseIf Status = "Disabled" Then
MessageBox.Show("disabled. Contact admin for more information.", "JKLorenzo", MessageBoxButtons.OK, MessageBoxIcon.Information)
Close()
End If
End If
End Sub
I finally made it to work
Here is the code i've used:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.ReportProgress(10)
Dim mysqlconnection As MySqlConnection = New MySqlConnection("server=85.10.205.173;port=3306;username='" & User & "';password='" & Pass & "'")
BackgroundWorker1.ReportProgress(20)
Dim mysqlcommand As MySqlCommand = Nothing
BackgroundWorker1.ReportProgress(30)
Dim mysqldatareader As MySqlDataReader = Nothing
BackgroundWorker1.ReportProgress(40)
mysqlconnection.Open()
BackgroundWorker1.ReportProgress(50)
Using table As DataTable = New DataTable
BackgroundWorker1.ReportProgress(60)
Using command As MySqlCommand = New MySqlCommand("Select * from my.accounts where Username = 'Ray';", mysqlconnection)
BackgroundWorker1.ReportProgress(70)
Using adapter As MySqlDataAdapter = New MySqlDataAdapter(command)
BackgroundWorker1.ReportProgress(80)
adapter.Fill(table)
BackgroundWorker1.ReportProgress(90)
End Using
End Using
For Each row As DataRow In table.Rows
If row("Flag") = "enable" Then
e.Result = "1"
BackgroundWorker1.ReportProgress(100)
Else
e.Result = "0"
BackgroundWorker1.ReportProgress(100)
End If
Next
End Using
mysqlconnection.Close()
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If e.ProgressPercentage = 10 Then
Label1.Text = "Status: Checking"
Label1.ForeColor = Color.FromKnownColor(KnownColor.Highlight)
End If
ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Refresh()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Threading.Thread.Sleep(500)
ProgressBar1.Value = 0
If e.Result = "1" Then
Label1.Text = "Status: Enabled"
Label1.ForeColor = Color.Green
Button1.Enabled = False
Button2.Enabled = True
ElseIf e.Result = "0" Then
Label1.Text = "Status: Disabled"
Label1.ForeColor = Color.OrangeRed
Button1.Enabled = True
Button2.Enabled = False
Else
MessageBox.Show("Unknown output: " & e.Result & " . Closing", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
Close()
End If
End Sub

My Update Method don't update any data in my database in vb.net using localdb

Sorry newbie here, I was making an inventory that could insert, delete and update. but the problem is all the data that i want to update don't really update. i always go to "Record Not Updated" then i try again to update the next problem occur is "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure."
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim iii As Integer
Try
cn.Open()
cmd.CommandText = "UPDATE service SET date=#date ,tech_assign=#tech_assign,err_one=#err_one,err_two= #err_two,err_tri = #err_tri,err_other = #err_other,err_other_spec = #err_other_spec,act_one = #act_one,act_two = #act_two,act_other = #act_other,act_other_spec = #act_other_spec,request = #request,op_unit = #op_unit WHERE serv_Id= #serv_Id"
cmd.Connection = cn
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Text)
cmd.Parameters.AddWithValue("#tech_assign", Tech_assignTextBox.Text)
cmd.Parameters.AddWithValue("#err_one", Err_oneCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_two", Err_twoCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_tri", Err_triCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_other", Err_otherCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_other_spec", Err_other_specTextBox.Text)
cmd.Parameters.AddWithValue("#act_one", Act_oneCheckBox.CheckState)
cmd.Parameters.AddWithValue("#act_two", Act_twoCheckBox.CheckState)
cmd.Parameters.AddWithValue("#act_other", Act_otherCheckBox.CheckState)
cmd.Parameters.AddWithValue("#act_other_spec", Act_other_specTextBox.Text)
cmd.Parameters.AddWithValue("#request", RequestTextBox.Text)
cmd.Parameters.AddWithValue("#op_unit", Op_unitTextBox.Text)
cmd.Parameters.AddWithValue("#serv_Id", i)
iii = cmd.ExecuteNonQuery()
If iii <> 0 Then
MsgBox("Record Updated Succesfully!", MessageBoxIcon.Information)
Else
MsgBox("Record Not Updated", MessageBoxIcon.Warning)
End If
cn.Close()
Me.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
#Steve Here is my whole code in the form, I use i from the datagridview from the other form
Imports System.Data
Imports System.Data.SqlClient
Public Class Form3
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\Carlo\Documents\Visual Studio 2013\Projects\WindowsApplication5\WindowsApplication5\db.mdf;Integrated Security=True")
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim aa As String
Dim i As Integer
Public Sub getText(ByVal a As String)
aa = a
End Sub
Public Sub getId(ByVal into As Integer)
into = i
End Sub
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If aa = "Save" Then
Button1.Enabled = True
Button1.Visible = True
Button2.Enabled = False
Button2.Visible = False
Me.DateDateTimePicker.Text = Now
Me.Tech_assignTextBox.Text = " "
Me.Err_oneCheckBox.CheckState = CheckState.Unchecked
Me.Err_twoCheckBox.CheckState = CheckState.Unchecked
Me.Err_triCheckBox.CheckState = CheckState.Unchecked
Me.Err_otherCheckBox.CheckState = CheckState.Unchecked
Me.Err_other_specTextBox.Text = " "
Me.Act_oneCheckBox.CheckState = CheckState.Unchecked
Me.Act_twoCheckBox.CheckState = CheckState.Unchecked
Me.Act_otherCheckBox.CheckState = CheckState.Unchecked
Me.Act_other_specTextBox.Text = " "
Me.RequestTextBox.Text = " "
Me.Op_unitTextBox.Text = " "
ElseIf aa = "Update" Then
Button1.Enabled = False
Button1.Visible = False
Button2.Enabled = True
Button2.Visible = True
Me.DateDateTimePicker.Text = Form2.ServiceDataGridView.Item(1, i).Value
Me.Tech_assignTextBox.Text = Form2.ServiceDataGridView.Item(2, i).Value
If Me.Err_oneCheckBox.CheckState = Form2.ServiceDataGridView.Item(3, i).Value = "False" Then
Me.Err_oneCheckBox.CheckState = CheckState.Checked
ElseIf Me.Err_oneCheckBox.CheckState = Form2.ServiceDataGridView.Item(3, i).Value = "True" Then
Me.Err_oneCheckBox.CheckState = CheckState.Unchecked
End If
If Me.Err_twoCheckBox.CheckState = Form2.ServiceDataGridView.Item(4, i).Value = "False" Then
Me.Err_twoCheckBox.CheckState = CheckState.Checked
ElseIf Me.Err_twoCheckBox.CheckState = Form2.ServiceDataGridView.Item(4, i).Value = "True" Then
Me.Err_twoCheckBox.CheckState = CheckState.Unchecked
End If
If Me.Err_triCheckBox.CheckState = Form2.ServiceDataGridView.Item(5, i).Value = "False" Then
Me.Err_triCheckBox.CheckState = CheckState.Checked
ElseIf Me.Err_triCheckBox.CheckState = Form2.ServiceDataGridView.Item(5, i).Value = "True" Then
Me.Err_triCheckBox.CheckState = CheckState.Unchecked
End If
If Me.Err_otherCheckBox.CheckState = Form2.ServiceDataGridView.Item(6, i).Value = "False" Then
Me.Err_otherCheckBox.CheckState = CheckState.Checked
ElseIf Me.Err_otherCheckBox.CheckState = Form2.ServiceDataGridView.Item(6, i).Value = "True" Then
Me.Err_otherCheckBox.CheckState = CheckState.Unchecked
End If
Me.Err_other_specTextBox.Text = Form2.ServiceDataGridView.Item(7, i).Value
If Me.Act_oneCheckBox.CheckState = Form2.ServiceDataGridView.Item(8, i).Value = "False" Then
Me.Act_oneCheckBox.CheckState = CheckState.Checked
ElseIf Me.Act_oneCheckBox.CheckState = Form2.ServiceDataGridView.Item(8, i).Value = "True" Then
Me.Act_oneCheckBox.CheckState = CheckState.Unchecked
End If
If Me.Act_twoCheckBox.CheckState = Form2.ServiceDataGridView.Item(9, i).Value = "False" Then
Me.Act_twoCheckBox.CheckState = CheckState.Checked
ElseIf Me.Act_twoCheckBox.CheckState = Form2.ServiceDataGridView.Item(9, i).Value = "True" Then
Me.Act_twoCheckBox.CheckState = CheckState.Unchecked
End If
If Me.Act_otherCheckBox.CheckState = Form2.ServiceDataGridView.Item(10, i).Value = "False" Then
Me.Act_otherCheckBox.CheckState = CheckState.Checked
ElseIf Me.Act_otherCheckBox.CheckState = Form2.ServiceDataGridView.Item(10, i).Value = "True" Then
Me.Act_otherCheckBox.CheckState = CheckState.Unchecked
End If
Me.Act_other_specTextBox.Text = Form2.ServiceDataGridView.Item(11, i).Value
Me.RequestTextBox.Text = Form2.ServiceDataGridView.Item(12, i).Value
Me.Op_unitTextBox.Text = Form2.ServiceDataGridView.Item(13, i).Value
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
cn.Open()
Using cmd As New SqlClient.SqlCommand("INSERT INTO service (date,tech_assign,err_one,err_two,err_tri,err_other,err_other_spec,act_one,act_two,act_other,act_other_spec,request,op_unit) VALUES(#date,#tech_assign,#err_one,#err_two,#err_tri,#err_other,#err_other_spec,#act_one,#act_two,#act_other,#act_other_spec,#request,#op_unit)", cn)
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Text)
cmd.Parameters.AddWithValue("#tech_assign", Tech_assignTextBox.Text)
cmd.Parameters.AddWithValue("#err_one", Err_oneCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_two", Err_twoCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_tri", Err_triCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_other", Err_otherCheckBox.CheckState)
cmd.Parameters.AddWithValue("#err_other_spec", Err_other_specTextBox.Text)
cmd.Parameters.AddWithValue("#act_one", Act_oneCheckBox.CheckState)
cmd.Parameters.AddWithValue("#act_two", Act_twoCheckBox.CheckState)
cmd.Parameters.AddWithValue("#act_other", Act_otherCheckBox.CheckState)
cmd.Parameters.AddWithValue("#act_other_spec", Act_other_specTextBox.Text)
cmd.Parameters.AddWithValue("#request", RequestTextBox.Text)
cmd.Parameters.AddWithValue("#op_unit", Op_unitTextBox.Text)
cmd.ExecuteNonQuery()
End Using
MsgBox("New Service Has Been Save", MessageBoxIcon.Information)
cn.Close()
Me.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Dim iii As Integer
Dim sqlText = "UPDATE service SET date=#date ,tech_assign=#tech_assign,err_one=#err_one,err_two= #err_two,err_tri = #err_tri,err_other = #err_other,err_other_spec = #err_other_spec,act_one = #act_one,act_two = #act_two,act_other = #act_other,act_other_spec = #act_other_spec,request = #request,op_unit = #op_unit WHERE serv_Id= #serv_Id"
Try
Using localCN = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\Carlo\Documents\Visual Studio 2013\Projects\WindowsApplication5\WindowsApplication5\db.mdf;Integrated Security=True")
Using localCMD = New SqlCommand(sqlText, localCN)
localCN.Open()
localCMD.Parameters.Add("#date", SqlDbType.Date).Value = DateDateTimePicker.Value
localCMD.Parameters.Add("#tech_assign", SqlDbType.NVarChar).Value = Tech_assignTextBox.Text
localCMD.Parameters.Add("#err_one", SqlDbType.Bit).Value = Err_oneCheckBox.CheckState
localCMD.Parameters.Add("#err_two", SqlDbType.Bit).Value = Err_twoCheckBox.CheckState
localCMD.Parameters.Add("#err_tri", SqlDbType.Bit).Value = Err_triCheckBox.CheckState
localCMD.Parameters.Add("#err_other", SqlDbType.Bit).Value = Err_otherCheckBox.CheckState
localCMD.Parameters.Add("#err_other_spec", SqlDbType.NVarChar).Value = Err_other_specTextBox.Text
localCMD.Parameters.Add("#act_one", SqlDbType.Bit).Value = Act_oneCheckBox.CheckState
localCMD.Parameters.Add("#act_two", SqlDbType.Bit).Value = Act_twoCheckBox.CheckState
localCMD.Parameters.Add("#act_other", SqlDbType.Bit).Value = Act_otherCheckBox.CheckState
localCMD.Parameters.Add("#act_other_spec", SqlDbType.NVarChar).Value = Act_other_specTextBox.Text
localCMD.Parameters.Add("#request", SqlDbType.NVarChar).Value = RequestTextBox.Text
localCMD.Parameters.Add("#op_unit", SqlDbType.NVarChar).Value = Op_unitTextBox.Text
localCMD.Parameters.Add("#serv_Id", SqlDbType.Int).Value = i
localCMD.ExecuteNonQuery()
localCN.Close()
End Using
End Using
'If iii <> 0 Then
'MsgBox("The Record Has Been Updated!", MessageBoxIcon.Information)
'Else
'MsgBox("The Record Is Not Updated!", MessageBoxIcon.Error)
'End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub form3_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
Form2.shwService()
End Sub
End Class
same problem occur on my first question,
Do not use global variables unless it is really necessary. In your case there is no need to keep a global connection object and a global command object. You don't loose any performance point if you declare the variables locally. Having a global SqlCommand object means that the parameters once assigned are still there the second time you enter this block of code. Instead a local object is always recreated as new and there are no remnants of the previous call.
The SqlConnection instance instead should be disposed as soon as possible to free system resources on your local machine and on the server also.
So your second problem could be solved in this way
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim iii As Integer
Dim sqlText = "UPDATE service SET date=#date, ......"
Try
Using localCN = new SqlConnection (.... your connection string....)
Using localCMD = new SqlCommand(sqlText, localCN)
localCN.Open()
localCMD.Parameters.Add("#date", SqlDbType.DateTime).Value = DateDateTimePicker.Date
.....
End Using
End Using
Catch ex as Exception
MsgBox(ex.Message)
' No need to add a Finally (Using statement close and dispose for you)
End Try
The first problem is, with high probability, caused by the fact that there is no record with a Serv_ID field matching your variable i at the moment of the call, another possibility is that you are working with a different database than you plan to use. In particular this happens a lot when you have used the |DataDirectory| substitution string in your connection string
EDIT
Looking at your update, it seems that you have this inverted
Public Sub getId(ByVal into As Integer)
' into = i
i = into
End Sub

Asset Dataset Button

I have been trying to write a program for a company that I work for, that would do assist tracking as well as give an overview of where the assists are.
The idea is to have a database with unique numbers on them that is allocated to all the hardware.
When a "desk" button is pressed it will show the info form that desk and it can be edited from there.
I roughly have what I was looking for, but I'm struggling with an issue when I update data, the data is somehow placed in the incorrect row...
E.g:
Desk Name : TL1
PC : 0001
monitor : 0002
Desk Name : TL2
PC : 0003
monitor : 0004
If I update the fist data entry alone it works fine.. however when I update the second entry it gets saved onto the first entry
E.g:
Desk Name : TL2
PC : 0003
monitor : 0004
Desk Name : TL2
PC : 0003
monitor : 0004
This is the code I have so far, any help would be very appreciated.
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Dim inc As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Lib_9th_NLDataSet.tblContacts' table. You can move, or remove it, as needed.
Me.TblContactsTableAdapter.Fill(Me.Lib_9th_NLDataSet.tblContacts)
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = \\elite03\IT\Assets\Lib 9th NL.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT Desk,Pc,Monitor,Keyboard,Phone,Laptop FROM tblcontacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Lib_9th_NL")
con.Close()
MaxRows = Lib_9th_NLDataSet.tblContacts.Rows(inc).Item(inc)
inc = 0
End Sub
Private Sub NavigateRecords()
txtDesk_Name.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(0)
txtPC.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(1)
txtMonintor.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(2)
txtKeyboard.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(3)
txtPhone.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(4)
txtlaptop.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(5)
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Me.Validate()
Me.TblContactsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Lib_9th_NLDataSet)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 0 Then
inc = inc + 1
NavigateRecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
Else
MsgBox("First Record")
End If
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
btnCommit.Enabled = True
btnUpdate.Enabled = False
btnDelete.Enabled = False
btnAddNew.Enabled = False
txtDesk_Name.Clear()
txtPC.Clear()
txtMonintor.Clear()
txtKeyboard.Clear()
txtPhone.Clear()
txtlaptop.Clear()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True
btnDelete.Enabled = True
inc = 0
NavigateRecords()
End Sub
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Lib_9th_NL").NewRow()
dsNewRow.Item("desk") = txtDesk_Name.Text
dsNewRow.Item("PC") = txtPC.Text
dsNewRow.Item("Monitor") = txtMonintor.Text
dsNewRow.Item("Keyboard") = txtKeyboard.Text
dsNewRow.Item("Phone") = txtPhone.Text
dsNewRow.Item("Laptop") = txtlaptop.Text
ds.Tables("Lib_9th_NL").Rows.Add(dsNewRow)
da.Update(ds, "Lib_9th_NL")
MsgBox("New Record added to the Database")
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True >
btnDelete.Enabled = True
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Lib_9th_NL").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "Lib_9th_NL")
NavigateRecords()
End Sub
Private Sub TL1_Click(sender As Object, e As EventArgs) Handles TL1.Click
txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(1)
txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(2)
txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(3)
txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(4)
txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(5)
txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(6)
End Sub
Private Sub Ret1_Click(sender As Object, e As EventArgs) Handles Ret1.Click
txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(1)
txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(2)
txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(3)
txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(4)
txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(5)
txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(6)
End Sub
End Class
It seems like you might be getting mixed up between your DataSet and your TableAdapterManager.
First, we need to get the values from the text boxes.
empID = EmployeeIDTxt.Text
dob = DateOfBirthTxt.Text
mailStation = MailStationTxt.Text
eFirst = FNameTxt.Text
prefName = PrefNameTxt.Text
eLast = LNameTxt.Text
homeAddress = Address1Txt.Text
city = CityTxt.Text
state = StateTxt.Text
zip = ZipTxt.Text
payGroup = PayGroupTxt.Text
fileNo = FileNoTxt.Text
begDT = BegDtTxt.Text
Now, we can reference the fields in our Update query as variables, and add parameters to them so we can prevent SQL Injection.
'This is your update statement
Dim updateQry As String = String.Empty
updateQry = "UPDATE YOURTABLE"
updateQry &= " SET EMPL_ID = #EmployeeID,EMPL_LAST_NM = #LastName, EMPL_FIRST_NM = #FirstName, EMPL_PREFRD_NM = #PrefName,"
updateQry &= " EMPL_BIRTH_DT = #DateOfBirth, EMPL_MAIL_STN_CD = #MS, EMPL_ADDR1_TXT = #HomeAddress,"
updateQry &= " EMPL_ADDR2_TXT = #Add2, EMPL_CITY_NM = #City, EMPL_STATE_CD = #State, EMPL_POSTL_CD = #Zip,"
updateQry &= " WHERE EMPL_ID = #EmployeeID ;"
'Declare Connection String
Using sqlConnection As New OleDBConnection(myConn)
Using cmd As New OleDBCommand()
'Declare variable for SQL command
With cmd
.Connection = sqlConnection
.CommandType = CommandType.Text
.CommandText = updateQry
'Prevent against SQL Injection -> Add Parameters
With .Parameters
.AddWithValue("#EmployeeID", empID)
.AddWithValue("#FirstName", eFirst)
.AddWithValue("#LastName", eLast)
.AddWithValue("#PrefName", prefName)
.AddWithValue("#DateOfBirth", dob)
.AddWithValue("#MS", mailStation)
.AddWithValue("#HomeAddress", homeAddress)
.AddWithValue("#City", city)
.AddWithValue("#State", state)
.AddWithValue("#Zip", zip)
End With
End With
Try
sqlConnection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error Updating " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Using
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MsgBox("" & FNameTxt.Text & " " & LNameTxt.Text & " has been updated")
End Try
Now, we need to change a few things.
Replace myConn with your connection string and open it in this instance (in the btnUpdate sub)
Change all of the fields in the Parameter list to your variables. ("EmployeeID" is the parameter I am providing for the variable empID)
Your WHERE clause is going to depend on what records you want to update. That's for you to decide. Is there a primary key you can reference like I do with EmployeeID?
Replace EMPL_ fields with your field names.
For clarification, the "#EmployeeID" parameter is the safe way of writing to the database of adding empID directly.
There are a couple other ways to do this, such as OleDbUpdateCommand, etc.
Hope this helps you.