How to 'Refresh' MS Access Database in Login Form vb.net? - vb.net

Imports System.Data.OleDb
Imports System.Data
Public Class frmLoginBP
Dim connection As New OleDbConnection(My.Settings.Business_ProfileConnectionString)
Private Sub lblInterfaceTypeTemp_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Format the timer.
lblDate.Text = Date.Now.ToString("dd-MM-yyyy hh:mm:ss")
End Sub
Private Sub lblDate_Click(sender As Object, e As EventArgs) Handles lblDate.Click
'Format the timer.
lblDate.Text = Date.Now.ToString("dd-MM-yyyy hh:mm:ss")
End Sub
Private Sub frmLoginBP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Show initial panels when loading the program.
Timer1.Enabled = True
Dim connection As New OleDbConnection(My.Settings.Business_ProfileConnectionString)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'button Register
frmRegistrationBP.Show()
End Sub
Private Sub btnShowPassword(sender As Object, e As EventArgs) Handles PictureBox3.Click
If txtBPPassword.UseSystemPasswordChar = True Then
txtBPPassword.UseSystemPasswordChar = False
Else
txtBPPassword.UseSystemPasswordChar = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtBPID.Text = "" Or txtBPPassword.Text = "" Then
MsgBox("Enter Credentials", MsgBoxStyle.Exclamation, "Error!")
Else
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim cmd As New OleDbCommand("select count(*) from [Business Details] where Email=? and Password=?", connection)
cmd.Parameters.AddWithValue("#1", OleDbType.VarChar).Value = txtBPID.Text
cmd.Parameters.AddWithValue("#2", OleDbType.VarChar).Value = txtBPPassword.Text
Dim count = Convert.ToInt32(cmd.ExecuteScalar())
If (count > 0) Then
MsgBox("Login succeed!", MsgBoxStyle.Information)
frmWelcomeNew.Show()
Me.Hide()
Else
MsgBox("Account not found. Check your credentials!", MsgBoxStyle.Critical, "Error!")
End If
End If
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
txtBPID.Text = ""
txtBPPassword.Text = ""
End Sub
End Class
First, I need to create an account in order to login into my system, thus, I press "Register" button. After I fill up the required textboxes,
Imports System.Data.OleDb
Public Class frmRegistrationBP
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Private Sub lblInterfaceTypeTemp_Click(sender As Object, e As EventArgs)
End Sub
Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
'Declare variable.
Dim opf As New OpenFileDialog
'Filter the file types.
opf.Filter = "Choose Image(*.jpg;*.png)|* .jpg;*.png"
If opf.ShowDialog = DialogResult.OK Then
'Assign the file to the picture box.
pcbBusinessPhoto.Image = Image.FromFile(opf.FileName)
End If
End Sub
Private Sub btnCancel_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnCancel_BizRegisPG1.Click
Me.Close()
End Sub
Private Sub btnReset_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnReset_BizRegisPG1.Click
txtBizAddress.Text = ""
txtBizAddress.Text = ""
txtBizName.Text = ""
txtBizPhoneNo.Text = ""
txtPassword.Text = ""
txtPasswordReenter.Text = ""
txtSSM.Text = ""
cboBizType.Text = ""
pcbBusinessPhoto.Image = Nothing
End Sub
Private Sub txtBizName_BizRegis_TextChanged(sender As Object, e As EventArgs) Handles txtBizName.TextChanged
End Sub
Private Sub btnNext_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnNext_BizRegisPG1.Click
If txtSQAnswer.Text = "" OrElse cboSQ.Text = "" OrElse txtSSM.Text = "" OrElse txtBizAddress.Text = "" OrElse txtBizEmail.Text = "" OrElse txtBizName.Text = "" OrElse txtBizPhoneNo.Text = "" OrElse txtPassword.Text = "" OrElse txtPasswordReenter.Text = "" OrElse cboBizType.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
ElseIf txtPasswordReenter.Text <> txtPassword.Text Then
MsgBox("Your Reentered Password is not the same!", MsgBoxStyle.Critical, "Error!")
Else
If IsNumeric(txtBizPhoneNo.Text) = False Then
MsgBox("Enter numeric value only in Company Phone Number", MsgBoxStyle.Critical, "Error!")
ElseIf IsNothing(pcbBusinessPhoto.image) Then
MsgBox("Please upload Business Photo", MsgBoxStyle.Critical, "Error!")
Else
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\chiac\OneDrive\Desktop\OMC\Code\[OMC] Business Partner\[OMC] Business Partner\Business Profile.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into [Business Details] values (#SSM,#BizName,#Address,#Email,#HP,#BizType,#Password,#BusinessPhoto,#OHFrom,#OHTo,#SQ1,SQ1Answer)"
Dim cmd As OleDbCommand = New OleDbCommand(Command, myconnection)
cmd.Parameters.Add(New OleDbParameter("#SSM", CType(UCase(txtSSM.Text), String)))
cmd.Parameters.Add(New OleDbParameter("#BizName", CType(txtBizName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Address", CType(txtBizAddress.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Email", CType(txtBizEmail.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#HP", CType(txtBizPhoneNo.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#BizType", CType(cboBizType.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Password", CType(txtPassword.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#BusinessPhoto", pcbBusinessPhoto.Image))
cmd.Parameters.Add(New OleDbParameter("#OHFrom", CType(cboOHFrom.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#OHTo", CType(cboOHTo.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#SQ1", CType(cboSQ.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#DQ1Answer", CType(txtSQAnswer.Text, String)))
MsgBox("Record Saved")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtSSM.Clear()
txtBizAddress.Clear()
txtBizEmail.Clear()
txtBizName.Clear()
txtBizPhoneNo.Clear()
txtPassword.Clear()
txtPasswordReenter.Clear()
cboBizType.Text = ""
cboOHFrom.Text = ""
cboOHTo.Text = ""
pcbBusinessPhoto.Image = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
frmRegistration2.Show()
Me.Hide()
End If
End If
End Sub
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub frmRegistrationBP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Imports System.Data.OleDb
Public Class frmRegistration2
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New OleDbConnection
Dim finalGender As String
Private Sub frmRegistration2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnUploadIC_Click(sender As Object, e As EventArgs) Handles btnUploadIC.Click
'Declare variable.
Dim opf As New OpenFileDialog
'Filter the file types.
opf.Filter = "Choose Image(*.jpg;*.png)|* .jpg;*.png"
If opf.ShowDialog = DialogResult.OK Then
'Assign the file to the picture box.
pcbIC.Image = Image.FromFile(opf.FileName)
End If
End Sub
Private Sub btnSubmit_BizRegisPG2_Click(sender As Object, e As EventArgs) Handles btnSubmit_BizRegisPG2.Click
If txtIC.Text = "" OrElse txtFirstName.Text = "" OrElse txtLastName.Text = "" OrElse txtEmail.Text = "" OrElse txtHP.Text = "" OrElse dtpDOB.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
Else
If IsNumeric(txtIC.Text) = False Then
MsgBox("Please insert numerical value in Identity Card Number!", MsgBoxStyle.Critical, "Error!")
ElseIf IsNothing(pcbIC.image) = True Then
MsgBox("Please insert Owner Photo!", MsgBoxStyle.Critical, "Error!")
ElseIf rbtFemale.Checked = False And rbtMale.Checked = False Then
MsgBox("Please select your gender!", MsgBoxStyle.Critical, "Error!")
ElseIf rbtAgree.Checked = False Then
MsgBox("Please AGREE with Goodstopia Terms & Conditions!", MsgBoxStyle.Critical, "Error!")
Else
If rbtMale.Checked = True Then
finalGender = "Male"
End If
If rbtFemale.Checked = True Then
finalGender = "Female"
End If
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\chiac\OneDrive\Desktop\OMC\Code\[OMC] Business Partner\[OMC] Business Partner\Business Profile.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into [Owner Details] values (#IC,#FirstName,#LastName,#Email,#HP,#DOB,#Gender,#ICPhoto)"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("#IC", CType(UCase(txtIC.Text), String)))
cmd.Parameters.Add(New OleDbParameter("#FirstName", CType(txtFirstName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#LastName", CType(txtLastName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Email", CType(txtEmail.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#HP", CType(txtHP.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#DOB", CType(dtpDOB.Text, String)))
cmd.Parameters.Add(New OleDbParameter("#Gender", finalGender))
cmd.Parameters.Add(New OleDbParameter("#ICPhoto", pcbIC.Image))
MsgBox("Record Saved")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtIC.Clear()
txtFirstName.Clear()
txtLastName.Clear()
txtHP.Clear()
txtEmail.Clear()
rbtFemale.Checked = False
rbtMale.Checked = False
pcbIC.Image = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Me.Hide()
frmLoginBP.Show()
End If
End Sub
Private Sub rbtAgreeTerms_BizRegis_CheckedChanged(sender As Object, e As EventArgs) Handles rbtAgree.CheckedChanged
End Sub
End Class
I press 'Submit', my MS Access Login Database has captured all the data I typed.
After that, The login form will reappear again. However, even though I had saved the details in my Login DB. I still can't manage to Login into my system. My guess is that it's because the Database in the Login form has not 'refreshed' yet.
So my question is How do I 'refresh' the database in my login form?

Connections use unmanaged resources which they release in their Dispose method. You must Dispose connections. Using...End Using blocks handle this for us. Declare connections in the method where the are used, not at the Class level. Declare the connection string at the class level so it can be used in any method in the class.
Don't include empty Subs in your question. The Timer and the date label have nothing to do with the question. Don't include these methods.
Enable your Timer at design time. It is pointless to create a local variable for a new connection in Form.Load and then let it fall out of scope before it is ever used. Remember, connections need to be disposed.
In the btnShowPassword method (which is strangely a picture box, why?) you can toggle a Boolean property in a single line.
In Button1.Click use OrElse to short circuit the If. It will stop evaluating expressions as soon as it finds a True.
Now to the database code. You will never need to check ConnectionState because it will be declared in the method in a Using block. Both the connection and the command are included in the Using block because commands need to be disposed too. Don't open the connection until directly before the .Execute...
I am happy to see the use of Parameters. I used the actual parameter name in the CommandText. The question mark works fine but it easier to tie the parameters to the ParametersCollection when you can see names. Access only pays attention to the position but it makes it easier to read.
The vb specific CInt has been optimized in .net.
The first code block should look like this.
Private ConStr As String = My.Settings.Business_ProfileConnectionString '"Your connection string"
Private Sub btnShowPassword(sender As Object, e As EventArgs) Handles PictureBox3.Click
txtBPPassword.UseSystemPasswordChar = Not txtBPPassword.UseSystemPasswordChar
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtBPID.Text = "" OrElse txtBPPassword.Text = "" Then
MsgBox("Enter Credentials", MsgBoxStyle.Exclamation, "Error!")
Else
Dim count As Integer
Using connection As New OleDbConnection(ConStr),
cmd As New OleDbCommand("select count(*) from [Business Details] where Email=#1 and Password=#2", connection)
cmd.Parameters.AddWithValue("#1", OleDbType.VarChar).Value = txtBPID.Text
cmd.Parameters.AddWithValue("#2", OleDbType.VarChar).Value = txtBPPassword.Text
connection.Open()
count = CInt(cmd.ExecuteScalar())
End Using
If count = 0 Then
MsgBox("Login succeed!", MsgBoxStyle.Information)
frmWelcomeNew.Show()
Me.Hide()
Else
MsgBox("Account not found. Check your credentials!", MsgBoxStyle.Critical, "Error!")
End If
End If
End Sub
In the second Form I am dividing up the code in btnNext.Click method.
It would be rare for a phone number to have no dashes or maybe ext. but I left it alone. I just got rid of the IsNumeric left over from vb6.
I am surprised that you are not using the settings that you used in the first form. This might be your problem.
You do not need to convert a Text property to a String. It is already a String.
Private ConStr As String = My.Settings.Business_ProfileConnectionString '"Your connection string"
Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(*.jpg;*.png)|* .jpg;*.png"
If opf.ShowDialog = DialogResult.OK Then
pcbBusinessPhoto.Image = Image.FromFile(opf.FileName)
End If
End Sub
Private Sub btnNext_BizRegisPG1_Click(sender As Object, e As EventArgs) Handles btnNext_BizRegisPG1.Click
If Not ValidateInput() Then
Exit Sub
End If
Try
InsertData()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
MsgBox("Record Saved")
ClearForm()
frmRegistration2.Show()
Me.Hide()
End Sub
Private Function ValidateInput() As Boolean
If txtSQAnswer.Text = "" OrElse cboSQ.Text = "" OrElse txtSSM.Text = "" OrElse txtBizAddress.Text = "" OrElse txtBizEmail.Text = "" OrElse txtBizName.Text = "" OrElse txtBizPhoneNo.Text = "" OrElse txtPassword.Text = "" OrElse txtPasswordReenter.Text = "" OrElse cboBizType.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If txtPasswordReenter.Text <> txtPassword.Text Then
MsgBox("Your Reentered Password is not the same!", MsgBoxStyle.Critical, "Error!")
Return False
End If
Dim Phone As Long
If Not Long.TryParse(txtBizPhoneNo.Text, Phone) Then
MsgBox("Enter numeric value only in Company Phone Number", MsgBoxStyle.Critical, "Error!")
Return False
End If
If IsNothing(pcbBusinessPhoto.image) Then
MsgBox("Please upload Business Photo", MsgBoxStyle.Critical, "Error!")
Return False
End If
Return True
End Function
Private Sub InsertData()
Using myconnection As New OleDbConnection(ConStr),
cmd As New OleDbCommand("insert into [Business Details] values (#SSM,#BizName,#Address,#Email,#HP,#BizType,#Password,#BusinessPhoto,#OHFrom,#OHTo,#SQ1,SQ1Answer)", myconnection)
cmd.Parameters.Add("#SSM", OleDbType.VarChar).Value = txtSSM.Text.ToUpper
cmd.Parameters.Add("#BizName", OleDbType.VarChar).Value = txtBizName.Text
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = txtBizAddress.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = txtBizEmail.Text
cmd.Parameters.Add("#HP", OleDbType.VarChar).Value = txtBizPhoneNo.Text
cmd.Parameters.Add("#BizType", OleDbType.VarChar).Value = cboBizType.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = txtPassword.Text
cmd.Parameters.Add("#BusinessPhoto", OleDbType.LongVarBinary).Value = pcbBusinessPhoto.Image))
cmd.Parameters.Add("#OHFrom", OleDbType.VarChar).Value = cboOHFrom.Text
cmd.Parameters.Add("#OHTo", OleDbType.VarChar).Value = cboOHTo.Text)
cmd.Parameters.Add("#SQ1", OleDbType.VarChar).Value = cboSQ.Text
cmd.Parameters.Add("#DQ1Answer", OleDbType.VarChar).Value = txtSQAnswer.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Private Sub ClearForm()
txtSSM.Clear()
txtBizAddress.Clear()
txtBizEmail.Clear()
txtBizName.Clear()
txtBizPhoneNo.Clear()
txtPassword.Clear()
txtPasswordReenter.Clear()
cboBizType.Text = ""
cboOHFrom.Text = ""
cboOHTo.Text = ""
pcbBusinessPhoto.Image = Nothing
End Sub
And for the third Form
Private ConStr As String = My.Settings.Business_ProfileConnectionString '"Your connection string"
Private Sub btnSubmit_BizRegisPG2_Click(sender As Object, e As EventArgs) Handles btnSubmit_BizRegisPG2.Click
If Not ValidateInput() Then
Return
End If
Try
InsertOwner()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
ClearForm()
MsgBox("Record Saved")
Me.Hide()
frmLoginBP.Show()
End Sub
Private Function ValidateInput() As Boolean
If txtIC.Text = "" OrElse txtFirstName.Text = "" OrElse txtLastName.Text = "" OrElse txtEmail.Text = "" OrElse txtHP.Text = "" OrElse dtpDOB.Text = "" Then
MsgBox("Please fill in the textboxes!", MsgBoxStyle.Critical, "Error!")
Return False
End If
Dim IC As Integer
If Not Integer.Parse(txtIC.Text, IC) Then
MsgBox("Please insert numerical value in Identity Card Number!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If pcbIC.image Is Nothing Then
MsgBox("Please insert Owner Photo!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If rbtFemale.Checked = False And rbtMale.Checked = False Then
MsgBox("Please select your gender!", MsgBoxStyle.Critical, "Error!")
Return False
End If
If rbtAgree.Checked = False Then
MsgBox("Please AGREE with Goodstopia Terms & Conditions!", MsgBoxStyle.Critical, "Error!")
Return False
End If
Return True
End Function
Private Sub InsertOwner()
Dim finalGender As String
If rbtMale.Checked = True Then
finalGender = "Male"
Else
finalGender = "Female"
End If
Dim Command = " insert into [Owner Details] values (#IC,#FirstName,#LastName,#Email,#HP,#DOB,#Gender,#ICPhoto)"
Using myconnection As New OleDbConnection(ConStr),
cmd As New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#IC", OleDbType.VarChar).Value = UCase(txtIC.Text)
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = txtFirstName.Text
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Email", OleDbType.VarChar).Value = txtEmail.Text
cmd.Parameters.Add("#HP", OleDbType.VarChar).Value = txtHP.Text
cmd.Parameters.Add("#DOB", OleDbType.VarChar).Value = dtpDOB.Text
cmd.Parameters.Add("#Gender", OleDbType.VarChar).Value = finalGender
cmd.Parameters.Add("#ICPhoto", OleDbType.LongVarBinary).Value = pcbIC.Image
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Private Sub ClearForm()
txtIC.Clear()
txtFirstName.Clear()
txtLastName.Clear()
txtHP.Clear()
txtEmail.Clear()
rbtFemale.Checked = False
rbtMale.Checked = False
pcbIC.Image = Nothing
End Sub
One more thing. Passwords should never be stored as plain text. Look up salting and hashing.

In your "register" method you explicitly put the connection string in code:
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\chiac\OneDrive\Desktop\OMC\Code\[OMC] Business Partner\[OMC] Business Partner\Business Profile.accdb"
In your login function you get it out of settings:
Dim connection As New OleDbConnection(My.Settings.Business_ProfileConnectionString)
(You also have the same code on the last line of Form Load, which is useless and should be removed)
--
I strongly suspect that these two connection strings point at different databases - your code is writing to a database, and you're opening it in access and seeing the data, but the app is looking in a different DB
If the settings mention |DataDirectory| or no absolute path, then the situation will potentially be even more confusing for you - you have a DB on your desktop, you have a DB in your project folder and you have a DB in your bin folder. If you ever make an update/insert that uses the connectionstring from settings, then you're editing the DB in the bin folder, but this DB is overwritten with a new copy of the DB from the project folder every time the app starts, so your changes are lost. Of course, in a production setting this doesn't happen because there is no bin folder or compilation process; it is merely a developer convenience (as a dev you're supposed to e.g. add new tables to the DB in the project folder)
Make sure your app is consistently looking in the same DB for all its operations (make your insert code use Settings too)

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"

Login form in VB.Net using Access database not working

I'm pretty sure this code used to allow me to login using the SQL statement below, but now it doesn't and just clears the text boxes.
There is also an error message that I would like displayed when the username and password do not match that in the database. This is, like the other one, a label that the visibility would need changing. I had this code:
Try
UserType = GetUserType(txtUsername.Text.Trim, txtPass.Text.Trim)
Catch ex As Exception
lblErrorMatch.Visible = True
End Try
However, this just clears the text boxes when the details do not match.
Imports System.Data.OleDb
Public Class frmLogin
Private DBCmd As New OleDbCommand
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;"
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim UserType As Object
'Distinguishing beetween different users
If UserType Is Nothing Then
lblErrorEmpty.Visible = True
ElseIf UserType.ToString = "MANAGER" Then
frmHomeManager.Show()
ElseIf UserType.ToString = "RECEPTIONIST" Then
frmHomeReceptionist.Show()
End If
'Username and password not matching error message
'Empty textboxes error message
If txtUsername.Text = "" OrElse txtPass.Text = "" Then lblErrorEmpty.Visible = True : Exit Sub
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Function GetUserType(Username As String, Pass As String) As Object
Dim UserType As Object
'Pull username and password from the database to check against the entered login details
Using DBCon As New OleDb.OleDbConnection(ConStr),
DBCmd As New OleDbCommand("SELECT UserType FROM tblEmployeeLogin WHERE [Username] = #Username AND [Pass] = #Pass", DBCon)
DBCmd.Parameters.Add("#Username", OleDbType.VarChar).Value = Username
DBCmd.Parameters.Add("#Pass", OleDbType.VarChar).Value = Pass
DBCon.Open()
UserType = DBCmd.ExecuteScalar.ToString
End Using
Return UserType
End Function
Private Sub chkShowPass_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPass.CheckedChanged
'Show password when checkbox is checked
If chkShowPass.Checked = True Then
txtPass.PasswordChar = Nothing
ElseIf chkShowPass.Checked = False Then
txtPass.PasswordChar = "*"
End If
End Sub
Private Sub txtUsername_TextChanged(sender As Object, e As EventArgs) Handles txtUsername.TextChanged, txtPass.TextChanged
'Make error message disappear after text is enetered into either of the text boxes
lblErrorEmpty.Visible = False
lblErrorMatch.Visible = False
End Sub
Private Sub lnkClear_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lnkClear.LinkClicked
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
'Close the form down which stops the application
Me.Close()
End Sub
End Class
Thank you for your time :)
I recently made a login like what you're trying to do. Hopefully you understand this code and it helps:
Dim CMD As OleDbCommand = New OleDbCommand("SELECT * FROM Staff WHERE Login = '" & ID & "'", Con)
Dim user As String
Try
Con.Open()
Dim sdr As OleDbDataReader = CMD.ExecuteReader()
If (sdr.Read() = True) Then
user = sdr("Login")
MessageBox.Show("Login Successful!")
ActiveUser.IsLoggedIn = True
Else
MessageBox.Show("Invalid username or password!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
Con.Close()
End Try

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

Please complete required fields message box

I'm trying to do a "Please complete required fields" messagebox.
Tt does show up but "Account Created" also pops out just right after "Please complete required fields" appears whenever I try entering even one character in a textbox or clicking one of the two radio button.
Also instead of "Please complete required fields", "User already exists!" shows up whenever the fields are empty.
Can somebody tell me what's wrong with my codes?
Thank you....
Public Class CreateAccount
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname, #pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
conn.Open()
Dim strUsername As String = TextBox1.Text
Dim boolUsernameExists As Boolean = False
Using dbConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb")
dbConnection.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", dbConnection)
dbCommand.Parameters.AddWithValue("#uname", strUsername)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result > 0 Then
boolUsernameExists = True
End If
End Using
dbConnection.Close()
End Using
If boolUsernameExists Then
MessageBox.Show("Username already exists!")
Return
End If
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
conn.Close()
If TextBox1.Text = "" Or TextBox2.Text = "" Or RadioButton1.Checked = False Or RadioButton2.Checked = False Then
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Hide()
LoginUser.Show()
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.Back '<--- this is for backspace
Case 13
e.Handled = True
SendKeys.Send("{TAB}") '<---- use to tab to next textbox or control
KeyAscii = 0
Case Is <= 32
' KeyAscii = 0
Case 48 To 57 '<--- this is for numbers
Exit Sub
Case 65 To 90 '<--- this is for Uppercase Alpha
Exit Sub
Case 97 To 122 '<--- this is for Lowercase Alpha
Exit Sub
Case Else
e.Handled = True
MessageBox.Show("You can only input letters and numbers!", "Create Account")
End Select
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
End Class
I agree with DavidSdot, your code is out of order.
Here is an example that might work. I say might because im not very good at vb.net. So you might need to change a few things to make it work. However, that being said, the following might do you well regarding the correct order in which it should go.
Try
Using conn = New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thesis\Thesis\Database2.accdb"
If ((TextBox1.Text <> "" And TextBox2.Text <> "") And (RadioButton1.Checked <> False Or RadioButton2.Checked <> False)) Then
conn.Open()
Using dbCommand As New System.Data.OleDb.OleDbCommand("select count(username) from tbl_user where username like ?", conn)
dbCommand.Parameters.AddWithValue("#uname", TextBox1.Text)
Dim result As Integer = DirectCast(dbCommand.ExecuteScalar(), Integer)
If result = 0 Then
Dim sql As String = "INSERT INTO tbl_user (username, [password],facultymember,student) " & _
"VALUES (#uname,#pwd,#fmem,#stud)"
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlCom.Parameters.AddWithValue("#uname", TextBox1.Text)
sqlCom.Parameters.AddWithValue("#pwd", TextBox2.Text)
sqlCom.Parameters.AddWithValue("#fmem", RadioButton1.Checked)
sqlCom.Parameters.AddWithValue("#stud", RadioButton2.Checked)
Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()
RadioButton1.Checked = False
RadioButton2.Checked = False
TextBox1.Text = ""
TextBox2.Text = ""
MessageBox.Show("Account created successfully!")
Me.Hide()
LoginUser.Show()
Else
MessageBox.Show("Username already exists!")
Return
End If
End Using
Else
MessageBox.Show("Please complete the required fields.", "Authentication Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error:" & ex.Message)
End Try
You should really take a look at the logic of Button1_click sub, because it is really hard to understand.
You opening your database twice
you already inserted a user with username="" and password="" thats why you get user exists message when you have not enter anything
Account created successfully! is always shown after Please complete the required fields as there is no check/return/whatever when fields as missing
No idea why the DB Insert is called on every keystroke as there is no code for that in what you posted

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.