Asset Dataset Button - sql

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.

Related

Access denied during production

The code below works as intended in DEBUG with no errors. I input my search parameters, the record returns and populates all textboxes and loads the PDF file into the AxAcroPDF1 viewer.
However, after I compile and install the program I am receiving the error "Access to the path 'C:\Program Files (x86)\NAME OF PROGRAM\temp.file' is denied'
This only occurs when I search for a record and the PDF (in Binary format in the DB) to that record is supposed to load fails with the error message listed above. How can I resolve the permissions level (assuming this is the issue) to allow for the PDF to load? The area of concern presumably and more specifically is the LoadPDF() sub.
My code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
'Loads last record on to form
DocumentsTableBindingSource.Position = DocDataset.Documents_Table.Rows.Count - 1
DV = New DataView(DocDataset.Documents_Table)
'LoadPDF()
End Sub
Private Sub BtnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
tbRecNumb.Clear()
tbFileName.Clear()
tbPetsLoadNumber.Clear()
tbBrokerLoadNumber.Clear()
tbFilePath.Clear()
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
' Search for PETS Load Number, Broker Load Numberthen load record if found
Private Sub BtnSearchBtn_MouseEnter(sender As Object, e As EventArgs) Handles btnSearch.MouseEnter
Cursor = Cursors.Hand
btnSearch.BackgroundImage = My.Resources.ButtonDwn_Teal_Trans
End Sub
Private Sub BtnSearchBtn_MouseLeave(sender As Object, e As EventArgs) Handles btnSearch.MouseLeave
Cursor = Cursors.Default
btnSearch.BackgroundImage = My.Resources.Button_Teal_Trans
End Sub
Private Sub TbSearchInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbSearchInput.KeyDown
Cursor = Cursors.Hand
If e.KeyCode = Keys.Enter Then
Search()
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.BackgroundImage = My.Resources.ButtonClk_Teal_Trans
Cursor = Cursors.Hand
Search()
End Sub
Private Sub Search()
Cursor = Cursors.WaitCursor
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
LoadPDF()
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
Cursor = Cursors.Default
End Sub
Private Sub LblSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub LoadPDF()
Dim temp = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User)
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT DOCUMENTS FROM Documents_Table WHERE PETS_LOAD_NUMBER = #pl"
cmd.Parameters.AddWithValue("#pl", tbPetsLoadNumber.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
Dim Buffer As Byte()
cmd.Connection.Open()
Buffer = cmd.ExecuteScalar
cmd.Connection.Close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = Application.StartupPath() & "\temp.file"
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, DOCUMENTS)
VALUES (#bl, #fn, #pl, #pdf)"
cmd.Parameters.Add("#fn", SqlDbType.NVarChar, 50).Value = tbFileName.Text
cmd.Parameters.Add("#pl", SqlDbType.Int).Value = tbPetsLoadNumber.Text
cmd.Parameters.Add("#bl", SqlDbType.NVarChar, 20).Value = tbBrokerLoadNumber.Text
cmd.Parameters.Add("#pdf", SqlDbType.VarBinary, -1).Value = data
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File Successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
In your function LoadPDF you create a reference to tempdir and then don't use it. Instead, you use Application.StartupPath() which will point to C:\Programs(x86) and is usually not writeable without admin rights.
But why don't you use your temp dir:
Dim temp = SpecialDirectories.Temp 'more robust approach to get tempdir
If File.Exists(temp & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(temp & "\temp.file")
End If
...
File.WriteAllBytes(temp & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = temp & "\temp.file"

Splitting data from database to 3 comboboxes

Hello there I wanted to ask if could you split to split data from my database and populate three textboxes. I have a column in my database called DOB (date of birth) its a Varchar I wanted to populate three combo boxes with the data from that column.The code is in the navigaterecord subprocedure. This is my code :
Imports System.Data.SQLite
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim ConnectionString As String = "Data Source=dbRoomBookings.db"
Dim ds As New DataSet
Dim dt As New DataTable
Dim mSQL As String = "SELECT * FROM Customer"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customer")
dt = ds.Tables(0)
MaxRows = ds.Tables("customer").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customer;"
dgvSearchResults.DataSource = display(msSQL, "customer")
MaxRows = ds.Tables("customer").Rows.Count
inc = -1
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Sub navigaterecords()
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(3) Then
cboYear.Text = ds.Tables("customer").Rows(inc).Item(3)
txtDbo.Text = ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(3)
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("no more rows")
End If
End Sub
Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
navigaterecords()
Else
End If
End Sub

how can i fix this error=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"

I have a gridview when i click the column of the dataGridview the problem show
"error=Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index""
how can i fix this? please help
this is the whole code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'construct dataGridview
DataGridView1.ColumnCount = 4
DataGridView1.Columns(0).Name = "name"
DataGridView1.Columns(1).Name = "position"
DataGridView1.Columns(2).Name = "team"
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect
End Sub
Private Sub Populate(name As String, pos As String, team As String)
Dim row As String() = New String() {name, pos, team}
DataGridView1.Rows.Add(row)
End Sub
Private Sub Retrieve()
DataGridView1.Rows.Clear()
Dim sql As String = "SELECT * FROM peopleTB"
cmd = New OleDbCommand(sql, con)
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.fill(dt)
'fill dgview
For Each row In dt.Rows
Populate(row(1), row(2), row(3))
Next
con.Close()
dt.Rows.Clear()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Cleartxt()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End Sub
'update db and dg
Private Sub UpdateDG(name As String)
Dim sql As String = "UPDATE peopleTB Set N ='" + TextBox1.Text + "',P='" + TextBox2.Text + "',T='" + TextBox3.Text + "'WHERE N= '" + name + "'"
'OPEN CON
Try
con.Open()
adapter.updateCommand = con.CreateCommand()
adapter.updateCommand.commandtext = sql
If adapter.updateCommand.executenonquery() > 0 Then
MsgBox("Success updated")
Cleartxt()
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim name As String = DataGridView1.SelectedRows(0).Cells(0).Value
Dim position As String = DataGridView1.SelectedRows(0).Cells(1).Value
Dim team As String = DataGridView1.SelectedRows(0).Cells(2).Value
TextBox1.Text = name
TextBox2.Text = position
TextBox3.Text = team
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim name As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(name)
End Sub
Im using ms access

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

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

Identifier expected? visual basic

im almost done with this and then that... hopefully someone will be able to help me (Really hope so atleast, cus i need to be done with this:P) (need more text cus there is to much code):
|error is there|>
Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlatButton1_Click. <|error is there|
Dim Conn As New MySqlConnection("Not going to publish this")
If FlatTextBox1.Text = "" Then
MsgBox("No username specified")
FlatTextBox2.Text = ""
Else
If FlatTextBox2.Text = "" Then
MsgBox("No password specified")
FlatTextBox1.Text = ""
Else
Try
Me.Text = "Logging in..."
Conn.Open()
Dim sqlquery As String = "SELECT * FROM Testing WHERE Username = '" & FlatTextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = Conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = FlatTextBox2.Text Then
Me.Text = "Logged in!"
My.Settings.Username = FlatTextBox1.Text
MsgBox("Welcome " + data(1).ToString)
Home.Show()
Me.Close()
If data(3).ToString = "1" Then
My.Settings.Admin = "Yes"
Else
My.Settings.Admin = "No"
End If
End If
Else
MsgBox("Failed Login")
End If
End While
Catch ex As Exception
End Try
End If
End If
End Sub
End Class
Replace these Lines
Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles FlatButton1_Click
With
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1_Click