How to create an Update button for a database? - vb.net

I have a problem concerning my Update button, I don't know where to start to make it update my SQL database, I use SSMS Microsoft to create my table Subjects and I also connected it with my VS 2010 ULTIMATE where I drag my table to LINQtoSQL and DATASET, I have created a Save button which successfully saves to my database and refreshes my datagridview.
[ Private Sub Button18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If txtSubjectName.Text = "" Then
ErrorProvider1.SetError(txtSubjectName, "Subject Name Cannot be Empty!")
Exit Sub
ElseIf txtSubSName.Text = "" Then
ErrorProvider2.SetError(txtSubSName, "Subject Short Name Cannot be Empty!")
Exit Sub
End If
Dim db As New EMSDataContext
Dim SaveSubject = From C In db.Subjects
Where C.SubjectName = txtSubjectName.Text
Select C
If SaveSubject.Count <> 0 Then
MsgBox("Subject already exits!!", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Alart!!")
Exit Sub
Else
Dim SaveNSubject As New Subject With {.SubjectName = txtSubjectName.Text, .ShortName = txtSubSName.Text}
db.Subjects.InsertOnSubmit(SaveNSubject)
db.SubmitChanges()
MsgBox("Subject added successfully!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Information")
End If
Registration_Load(sender, e)
txtSubjectName.Text = ""
txtSubSName.Text = ""
End Sub]
And I also have a Delete button which successfully deletes my data from database and refreshes my datagridview.
[Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim A As New EMSDataContext
Dim B = From C In A.Subjects
Where C.ID = Val(DtgvSubject.CurrentRow.Cells(0).Value)
Select C
Try
A.Subjects.DeleteOnSubmit(B.FirstOrDefault)
If MsgBox("Are You Sure to Delete This Record?", MsgBoxStyle.Question + vbYesNo, "Question") = MsgBoxResult.Yes Then
A.SubmitChanges()
MsgBox("Record Deleted Successfully!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Information")
txtSubjectName.Text = ""
txtSubSName.Text = ""
Registration_Load(sender, e)
Else
txtSubjectName.Text = ""
txtSubSName.Text = ""
Registration_Load(sender, e)
End If
Catch ex As Exception
MsgBox("Select a Record First!", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "ALERT!!!")
End Try
If B.Count = 0 Then
MsgBox("Please select list to delete!", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Alart!!")
End If
End Sub]
I also created a double click Events of the datagridview cell where I get cells values to my Subject Name textbox and Subject Short Name textbox if I double clicked which is also successfull.
[ Private Sub DtgvSubject_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DtgvSubject.CellDoubleClick
Try
Dim i As Integer
i = DtgvSubject.CurrentRow.Index
Me.txtSubjectName.Text = DtgvSubject.Item(1, i).Value
Me.txtSubSName.Text = DtgvSubject.Item(2, i).Value
Catch ex As Exception
MsgBox("No Values in the Cells!", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Alert!!!")
Button17_Click(sender, e)
End Try
End Sub]
My Question is, how can I create an Update button to my Database after getting the Values to the Textboxes and update them, Submit Changes and refresh my datagridview?

Assuming your inputs are not bound to the dataset, you just need to retrieve the existing record from the database, update the record and save it again. Something like this should work:
public Function updaterecord (field1 as integer, field2 as text) as Object
Dim db As New EMSDataContext
Dim SaveSubject = From C In db.Subjects
Where C.SubjectName = txtSubjectName.Text
Select C
if SaveSubject is not Nothing then
C.id = field1
C.name = field2 'etc etc
End if
db.SaveChanges()
return
From C In db.Subjects
Where C.SubjectName = txtSubjectName.Text
Select C
End Function

Thank you Haim i have solved the Problem using LinqtoSQL
[ Private Sub bnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnUpdate.Click
If txtClassTeacher.Text = "" Or txtClassName.Text = "" Or txtClassSName.Text = "" Or cboClassSection.Text = "" Then
MsgBox("Select the data you want Update Please!", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "ALERT!!!")
Exit Sub
End If
Dim db As New EMSDataContext
Dim SaveClasses = From c In db.Classtbls
Where c.ID = Val(DtgvClasstbl.CurrentRow.Cells(0).Value)
Select c
For Each c As Classtbl In SaveClasses
c.Class_Teacher = txtClassTeacher.Text
c.Class_Name = txtClassName.Text
c.Short_Name = txtClassSName.Text
c.Section = cboClassSection.Text
'Inserting additional changes
Next
'Submitting changes to the Database
Try
If MsgBox("Are You Sure You Want Update This Record?", MsgBoxStyle.Question + vbYesNo, "Question") = MsgBoxResult.Yes Then
db.SubmitChanges()
MsgBox("Data Successfully Updated!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Success!")
Registration_Load(sender, e)
txtClassTeacher.Text = ""
txtClassName.Text = ""
txtClassSName.Text = ""
cboClassSection.Text = ""
Else
Registration_Load(sender, e)
txtClassTeacher.Text = ""
txtClassName.Text = ""
txtClassSName.Text = ""
cboClassSection.Text = ""
End If
Catch ex As Exception
MsgBox("Update not Successful!", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "ALERT!!!")
'Making(Adudjstiment)
db.SubmitChanges()
End Try
End Sub]
Thank you StackOverflow and MSDN for guidance

Related

For me to be able to select all the row in datagridview

For me to be able to select all rows in my datagrid and after i select all the row the next step im going to do is to save all the rows i have selected in other table through database now im using a checkbox to select all the rows i have the code for checking all the checkbox my problem is the saving to save all the rows that ive checked in just one button
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim countCheckDatas As Integer = 0
If e.RowIndex = -1 Then
'----------Check if all datagridview columns as checked----------
For count = 0 To DataGridView1.RowCount - 1
If DataGridView1.Rows(count).Cells(e.ColumnIndex).Value = True Then
countCheckDatas += 1
End If
Next
If countCheckDatas <> DataGridView1.RowCount Then
If MsgBox("Do you want to check all checkbox ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Check all") = MsgBoxResult.Yes Then
For DGVCols = 0 To DataGridView1.RowCount - 1
DataGridView1.Rows(DGVCols).Cells(e.ColumnIndex).Value = True
Next
End If
Else
If MsgBox("Do you want to uncheck all checkbox ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Uncheck all") = MsgBoxResult.Yes Then
For DGVCols = 0 To DataGridView1.RowCount - 1
DataGridView1.Rows(DGVCols).Cells(e.ColumnIndex).Value = False
Next
End If
End If
End If
End Sub
Hi Jhen i just finish the code, just replace this code into your button to store all the data and display it on a new datagridview...
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
For i = 0 To DataGridView1.RowCount - 1
If DataGridView1.Rows(i).Cells(1).Value = True Then
txtattendance.Text = DataGridView1.Item(2, i).Value
txtnames.Text = DataGridView1.Item(3, i).Value
txtsection.Text = DataGridView1.Item(4, i).Value
txtclasssubject.Text = DataGridView1.Item(5, i).Value
txttimein.Text = DataGridView1.Item(6, i).Value
txtinstructorname.Text = DataGridView1.Item(7, i).Value
txtclasstime.Text = DataGridView1.Item(8, i).Value
txttimeout.Text = TimeOfDay
Me.DataGridView2.Rows.Add(Me.txtattendance.Text, Me.txtnames.Text, Me.txtsection.Text, Me.txtclasssubject.Text, Me.txttimein.Text, Me.txttimeout.Text, Me.txtinstructorname.Text, Me.txtclasstime.Text)
myconnection.Open()
'Declaration of Variables
Dim str As String
Dim vAttendance As String
Dim vNames As String
Dim vSection As String
Dim vClassSubject As String
Dim vTimeIn As String
Dim vTimeOut As String
Dim vInstructorName As String
Dim vClassTime As String
vAttendance = txtattendance.Text
vNames = txtnames.Text
vSection = txtsection.Text
vClassSubject = txtclasssubject.Text
vTimeIn = txttimein.Text
vTimeOut = txttimeout.Text
vInstructorName = txtinstructorname.Text
vClassTime = txtclasstime.Text
str = "Insert into DATA ([Attendance],[Names],[Section],[ClassSubject],[TimeIn],[TimeOut],[InstructorName],[ClassTime]) values (?,?,?,?,?,?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myconnection)
cmd.Parameters.AddWithValue("#Attendance", vAttendance)
cmd.Parameters.AddWithValue("#Names", vNames)
cmd.Parameters.AddWithValue("#Section", vSection)
cmd.Parameters.AddWithValue("#ClassSubject", vClassSubject)
cmd.Parameters.AddWithValue("#TimeIn", vTimeIn)
cmd.Parameters.AddWithValue("#TimeOut", vTimeOut)
cmd.Parameters.AddWithValue("#InstructorName", vInstructorName)
cmd.Parameters.AddWithValue("#ClassTime", vClassTime)
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
End If
Next
MessageBox.Show("You Just Had Time Out , On Your Class!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As OleDb.OleDbException
MsgBox(ex.Message, MsgBoxStyle.Critical, "oledb Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
And Also Change The DataGridView1 Code To This...
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim countCheckDatas As Integer = 0
If e.RowIndex = -1 And e.ColumnIndex = 1 Then
'----------Check if all datagridview columns as checked----------
For count = 0 To DataGridView1.RowCount - 1
If DataGridView1.Rows(count).Cells(e.ColumnIndex).Value = True Then
countCheckDatas += 1
End If
Next
If countCheckDatas <> DataGridView1.RowCount Then
If MsgBox("Do you want to check all checkbox ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Check all") = MsgBoxResult.Yes Then
For DGVCols = 0 To DataGridView1.RowCount - 1
DataGridView1.Rows(DGVCols).Cells(e.ColumnIndex).Value = True
Next
End If
Else
If MsgBox("Do you want to uncheck all checkbox ?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Uncheck all") = MsgBoxResult.Yes Then
For DGVCols = 0 To DataGridView1.RowCount - 1
DataGridView1.Rows(DGVCols).Cells(e.ColumnIndex).Value = False
Next
End If
End If
End If
End Sub
one more thing,
I Saw the Connection String to the MS access but the location is not valid, the MS Access DB is located in your Project folder...
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'DataFile = "E:\Mytime\TIMEandOUT\TIMEandOUT\bin\Debug\BackUp\Testing.accdb"
DataFile = My.Application.Info.DirectoryPath.ToString() & "\BackUp\testing.Accdb;Persist Security Info=False;"
Best Regards,

avoid data redundancy on ms access using vb 2010

I need some help with regards on how to identify if the info that i will input on my database is existing or has the same record on my database..Pls i need some help... thank you
here is my code for SAVE BUTTON
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
rs = New ADODB.Recordset
With rs
'check if important item is null '
If txtappln.Text = "" Or txtappfn.Text = "" Or txtappmn.Text = "" Or txtclass.Text = "" Or txtcnum.Text = "" Or txtaddr.Text = "" Or txtbrgy.Text = "" Then
MsgBox("Some object in the Applicant Personal Information or Classification or Ctrl Number is not filled up", MessageBoxIcon.Warning)
.Cancel()
Else
'Save'
.Open("Select * from Applicant", con, 2, 3)
.AddNew()
.Fields("LAST_NAME").Value = txtappln.Text
.Fields("FIRST_NAME").Value = txtappfn.Text
.Fields("MIDDLE_NAME").Value = txtappmn.Text
.Fields("ADDRESS").Value = txtaddr.Text
.Fields("CLASSIFICATION").Value = txtclass.Text
.Fields("CONTROL_NO").Value = txtcnum.Text
.Fields("BARANGAY").Value = txtbrgy.Text
MsgBox("Record has been save !!", vbInformation)
.Update()
.Close()
End If
End With`

Get specific value from database to validate data

I want to take a value entered by the user and validate it against known values in a database.
I'm using VB.net (VS 2010) as a front end winform and dumping data into MSAccess. I have a table with values such as min weight and max weight, the user will enter a weight, and it needs to fall between the min weight and max weight values in the table.
I'm already created an open connection with the database I need, I guess I just don't know enogh VB.net and SQL to make it do what I want.
I want to have the user enter the Primary key of the table with the min weight and max weights and then use that to bring in the min max weights, then check the weight the user entered against the min max weights.
Here is all the code; the only really relevant code is the validate button click at the bottom. I just thought possibly this would give more context. Any point in the right direction will help, even if it gives me better keywords to google. Thanks!
Imports System.Data.OleDb
Public Class Form1
Dim dbInsert As New OleDb.OleDbCommand
Dim dbConnect As New OleDb.OleDbConnection
Dim Line As String = Environment.NewLine
Dim Job As VariantType
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
dbConnect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\crabara\Desktop\Project Alpha 3\MDB.accdb;Persist Security Info=False;"
dbConnect.Open()
Catch ex As Exception
MessageBox.Show(ex.Message + Line + "Main Database Not Found" + Line + "Check form_AccessMaintenance source code" + Line + "Database Path", "Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End Sub
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Part As String, Job As String, Emp As String, Weight As String, Oven As String
Part = txtPart.Text
Job = txtJob.Text
Emp = txtEmp.Text
Weight = txtWeight.Text
Oven = txtOven.Text
If ((Job.StartsWith("JH") And Job.Length = 10) Or Job.Equals("MT")) = False Then
MsgBox("Please input the correct Job Number.")
txtJob.Clear()
txtJob.Focus()
Exit Sub
ElseIf Part.Length = 0 Then
MsgBox("Please input the correct Part Number.")
txtPart.Clear()
txtPart.Focus()
Exit Sub
ElseIf Emp.Length = 0 Then
MsgBox("Please input the correct Employee Number.")
txtEmp.Clear()
txtEmp.Focus()
Exit Sub
ElseIf Weight.Length = 0 Then
MsgBox("Please input the correct Weight.")
txtWeight.Clear()
txtWeight.Focus()
Exit Sub
ElseIf Oven.Length = 0 Then
MsgBox("Please input the correct Oven Number.")
txtOven.Clear()
txtOven.Focus()
Exit Sub
End If
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Part"
dbInsert.Parameters.Item("Part").Value = txtPart.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Job"
dbInsert.Parameters.Item("Job").Value = txtJob.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Emp"
dbInsert.Parameters.Item("Emp").Value = txtEmp.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Weight"
dbInsert.Parameters.Item("Weight").Value = txtWeight.Text
dbInsert.Parameters.Add(dbInsert.CreateParameter).ParameterName = "Oven"
dbInsert.Parameters.Item("Oven").Value = txtOven.Text
Try
dbInsert.CommandText = "INSERT INTO Foam(Part,Job,Emp,Weight,Oven) VALUES(txtPart.Text, txtJob.Text, txtEmp.Text, txtWeight.Text, txtOven.Text);"
dbInsert.CommandType = CommandType.Text
dbInsert.Connection = dbConnect
dbInsert.ExecuteNonQuery()
MessageBox.Show("Data has been successfully submitted" + Line + txtPart.Text)
txtPart.Clear()
txtJob.Clear()
txtEmp.Clear()
txtWeight.Clear()
txtOven.Clear()
Control.MousePosition.Equals(txtPart)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub txtJob_GotFocus(sender As Object, e As System.EventArgs)
txtJob.Clear()
End Sub
Private Sub txtJob_LostFocus(sender As Object, e As System.EventArgs)
Dim Job2 As String
Job2 = txtJob.Text
If txtJob.Text.Length = 8 Then
txtJob.Text = "JH" + Job2
End If
End Sub
Private Sub btnValidate_Click_1(sender As System.Object, e As System.EventArgs) Handles btnValidate.Click
Dim Pcr As Integer
Pcr = txtPcr.Text
Try
dbInsert.CommandText = "SELECT MoldVinylWeightMin FROM PROCESS_INFO where PCRNumber= '" & txtPcr.Text & "'"""
'How can I get this data I've selected into a variable I can work with, also not sure if the above command actually works also this only gives me the min I need the max too
dbInsert.CommandType = CommandType.Text
dbInsert.Connection = dbConnect
dbInsert.ExecuteNonQuery()
MessageBox.Show("Data has been successfully submitted" + Line + txtPart.Text)
Catch ex As Exception
End Try
End Sub
End Class
I think below code will help you
Dim table = New DataTable()
Dim adp As New System.Data.OleDb.OleDbDataAdapter("SELECT MoldVinylWeightMin FROM PROCESS_INFO where PCRNumber= '" & txtPcr.Text & "'", dbConnect)
adp.Fill(table)
If table.Rows.Count <> 0 Then
If table.Rows(0).Item("MoldVinylWeightMin") <> YourField Then
Display the message
End If
Else
No record found
End If
using this block you can get the record from the database and apply you validation.

combobox search invalidargument=value of '0' is not valid for 'index'. parameter name index vb.net

i am using a textbox to search in an access database and then to show the matches in combobox , it is working fine but there is an error accrued when the user enters not matched entry ,
this is my code :
Private Sub TextBox9_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox9.TextChanged
Try
ComboBox3.DataSource = Me.MyDataset.Items.Select("ItemName like '%" & TextBox9.Text & "%'")
ComboBox3.Update()
If ComboBox3.Items.Count <> 0 Then
ComboBox3.DroppedDown = True
Me.Cursor = Cursors.Default
Cursor.Show()
Else
If ComboBox3.DroppedDown = True Then
ComboBox3.DroppedDown = False
End If
End If
If TextBox9.Text = "" Then
ComboBox3.DroppedDown = False
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Error")
End Try
End Sub
and when the user enters wrong entry or not matched this error appear :
invalidargument=value of '0' is not valid for 'index'. parameter name index vb.net
the question is how to handle this error
You should check if your datasource contains items before binding them to the ComboBox.
I don't know what type MyDataset is, but with Option Infer On the following should work, otherwise you should change the Dim dataSource = line to include the type.
Private Sub TextBox9_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox9.TextChanged
Try
Dim dataSource = Me.MyDataset.Items.Select("ItemName like '%" & TextBox9.Text & "%'")
If dataSource.Items.Count > 0 Then
ComboBox3.DataSource = datasource
ComboBox3.Update()
End If
If ComboBox3.Items.Count <> 0 Then
ComboBox3.DroppedDown = True
Me.Cursor = Cursors.Default
Cursor.Show()
Else
If ComboBox3.DroppedDown = True Then
ComboBox3.DroppedDown = False
End If
End If
If TextBox9.Text = "" Then
ComboBox3.DroppedDown = False
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Error")
End Try
End Sub

SQL Troubleshooting in VB.Net

Alright, here is my issue.
Working on a Inventory Control program, and got it mostly done, when a wild bug appears.
The system will check out a item, but will not check it back in, even though it throws all the proper messages that it does check the item in.
What's worse, is that the SQL statement is encapsulated in a try-catch class and acts as if nothing is wrong, and does not throw an exception.
And this is just a functional build, not a streamlined one, so it looks a little rough.
The statement in question is:
Dim OleCheckIn As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked In' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
I am sure it is something very very obvious, but I have been rebuilding and staring at it for so long, I am likely glossing over a glaring hole in it.
Option Strict On
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Public EmpIDFlag As Boolean
Public ItemBCode As Boolean
Public CheckFlag As Boolean
Public dEmpID As Double
Public sEmpID As String
Public dbEmpID As Double
Public dBarcode As Double
Public sBarcode As String
Public sFirstName As String
Public sLastName As String
Public sFullName As String
Public sItem As String
Public sCheckedOut As String
Public sCheckedOutBy As String
Public OleDbConn As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\rcassel\Documents\Visual Studio 2012\Projects\Inventory Control\Inventory Control\Inventory Control2.accdb;")
Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus
dEmpID = (Val(TextBox1.Text))
'Checks to see if someone entered a Badge
If dEmpID = Nothing Then
MsgBox("You must scan your Badge!", MsgBoxStyle.OkOnly)
TextBox1.Focus()
Else
sEmpID = dEmpID.ToString
'Fire Query into Database
Try
OleDbConn.Open()
Dim OleEmp As New OleDbCommand("SELECT [First Name],[Last Name],[Employee ID] FROM Contacts WHERE [Employee ID]=" + sEmpID + "", OleDbConn)
Dim r1 As OleDbDataReader = OleEmp.ExecuteReader()
While r1.Read()
sFirstName = CStr(r1("First Name"))
sLastName = CStr(r1("Last Name"))
dbEmpID = CInt(r1("Employee ID"))
End While
r1.Close()
Catch ex As Exception
'MsgBox("Cannot Pull Data." & vbCrLf & ex.Message)
End Try
If dbEmpID = Nothing Then
MsgBox("You are not Authorised to use this device. This activity has been logged.", MsgBoxStyle.OkOnly)
Else
Me.ListBox1.Items.Add(sFirstName)
Me.ListBox1.Items.Add(sLastName)
Me.ListBox1.Items.Add(sEmpID)
TextBox2.Focus()
End If
OleDbConn.Close()
End If
End Sub
'Item Barcode
'Private Sub TextBox2_LostFocus(sender As Object, e As EventArgs) Handles TextBox2.LostFocus
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
dBarcode = (Val(TextBox2.Text))
If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
sBarcode = dBarcode.ToString()
OleDbConn.Open()
Try
Dim OleItem As New OleDbCommand("SELECT [Item],[Checked Out],[Checked out Last by] FROM Assets WHERE [ID Number]=" + sBarcode + "", OleDbConn)
Dim r2 As OleDbDataReader = OleItem.ExecuteReader()
While r2.Read()
sItem = CStr(r2("Item"))
sCheckedOut = CStr(r2("Checked Out"))
sCheckedOutBy = CStr(r2("Checked out Last by"))
End While
ItemBCode = True
'Set Checkout Flag, this will be called later by the Check In/Check Out button
If sCheckedOut = "Checked Out" Then
CheckFlag = True
End If
r2.Close()
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
If ItemBCode = True Then
Me.ListBox2.Items.Add(sItem)
Me.ListBox2.Items.Add(sCheckedOut)
Me.ListBox2.Items.Add(sCheckedOutBy)
End If
OleDbConn.Close()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Focus()
End Sub
'This is the "Check In" button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If ItemBCode = False Then
MsgBox("You must have a Valid Item Barcode!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
Else
If CheckFlag Then
Try
OleDbConn.Open()
Dim OleCheckIn As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked In' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
MsgBox("This Item has been Checked in!", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
Else
MsgBox("This Item is already Checked in!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
End If
End If
OleDbConn.Close()
End Sub
'This is the "Check Out" button
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If ItemBCode = False Then
MsgBox("You must have a Valid Item Barcode!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
Else
If CheckFlag = False Then
Try
sFullName = String.Format("{0} {1}", sFirstName, sLastName)
OleDbConn.Open()
Dim OleCheckOut As New OleDbCommand("UPDATE Assets SET [Checked Out]='Checked Out',[Checked out Last by] ='" + sFullName + "' WHERE [ID Number]=" + sBarcode + "", OleDbConn)
MsgBox("This Item has been Checked Out!", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Barcode Invalid." & vbCrLf & ex.Message)
ItemBCode = False
End Try
Else
MsgBox("This Item is already Checked Out!", MsgBoxStyle.OkOnly)
TextBox2.Focus()
End If
End If
OleDbConn.Close()
End Sub
End Class
You never execute your update commands:
OleCheckIn.ExecuteNonQuery()
OleCheckOut.ExecuteNonQuery()
Also, use parameters. You are exposing your system to SQL injection.