error when update data ms access using visual basic 2010 - ms-access

**i have simple application, but i dont know how to fix it.
this pic when i try to edit my database--> http://i861.photobucket.com/albums/ab171/gopak/sa_zps5a950df5.jpg
when i click button edit i want my access data will be update.this is my code..
thanks for your advice**
Imports System.Data.OleDb
Public Class Form2
Public cnstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gop's\Downloads\admin site\admin site\admin site\bin\Debug\data_ruangan.accdb"""
Public cn As New OleDbConnection
Public cmd As New OleDbCommand
Public adaptor As New OleDbDataAdapter
Private Sub logout_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logout_btn.Click
Form1.Show()
Me.Close()
End Sub
Private Sub exit_btn_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exit_btn.Click
Dim a As Integer
a = MsgBox("Are you sure want to exit application?", vbInformation + vbYesNo, "Admin Site Virtual Tour Application")
If a = vbYes Then
End
Else
Me.Show()
End If
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Data_ruanganDataSet.data_ruangan' table. You can move, or remove it, as needed.
Me.Data_ruanganTableAdapter.Fill(Me.Data_ruanganDataSet.data_ruangan)
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i = DataGridView1.CurrentRow.Index
Label7.Text = DataGridView1.Item(0, i).Value
txtName.Text = DataGridView1.Item(1, i).Value
txtLocation.Text = DataGridView1.Item(2, i).Value
txtCapacity.Text = (DataGridView1.Item(3, i).Value).ToString
txtOperational.Text = (DataGridView1.Item(4, i).Value).ToString
txtInformation.Text = DataGridView1.Item(5, i).Value
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'If txtName.Text <> "" And txtLocation.Text <> "" And txtCapacity.Text <> "" And txtOperational.Text <> "" And txtInformation.Text <> "" Then
Dim i = DataGridView1.CurrentRow.Index
Dim ID = DataGridView1.Item(0, i).Value
Dim cmd As New OleDb.OleDbCommand
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
cmd.Connection = cn
cmd.CommandText = ("update data_ruangan set Name = '" & txtName.Text & _
"',Location = '" & txtLocation.Text & "',Capacity = '" & txtCapacity.Text & _
"',Operational_Hours ='" & txtOperational.Text & "',Information = '" & txtInformation.Text & ";")
cmd.ExecuteNonQuery()
cn.Close()
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
'End If
End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class

Try to use a parameterized query to execute your code. The error message is relative to the fact that you haven't initialized your connection with the information contained in the ConnectionString.
Here an example on how to do that...... but......
Dim cmdText = "update data_ruangan set [Name] = ?,Location = ?,Capacity = ?, " & _
"Operational_Hours =?,Information = ?;"
Using cn = new OleDbConnection( cnstring )
Using cmd = OleDb.OleDbCommand(cmdText, cn)
cn.Open
cmd.Parameters.AddWithValue("#p1", txtName.Text)
cmd.Parameters.AddWithValue("#p2", txtLocation.Text)
cmd.Parameters.AddWithValue("#p3", txtCapacity.Text)
cmd.Parameters.AddWithValue("#p4", txtOperational.Text)
cmd.Parameters.AddWithValue("#p5", txtInformation.Text)
'''' WARNING ''''
' WITHOUT A WHERE STATEMENT YOUR QUERY WILL UPDATE
' THE WHOLE TABLE WITH THE SAME VALUES
'''' WARNING ''''
cmd.ExecuteNonQuery()
End Using
End Using
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
This code updates all the records of your table with the same value, so, unless you have only one record and update Always the same record you need to add a WHERE condition to your command.
Also, the NAME word is a reserved keyword in Access 2007/2010 and it is better to encapsulate that word with square brackets to avoid a syntax error message.
I have also removed the global variable OleDbConnection and used a local one that will be closed and destroyed when the code exits from the Using statement. This is the correct way to handle disposable objects, in particular every connection object is Always to be used in this way to release as soon as possible the expensive unmanaged resource used by the object.

Related

VB2013 & MySQL not talking properly and program freezing

I have been working on a small project for a while now - it takes a plain text input from an Ardiuno Board (simple text, only a few characters). It's a simple NFC Card tagging program. The program is supposed to take the input from the SerialPort and check the input text against a MySQL database. If it finds the name in the database, then it is to update one column, that's it.
The problem is two fold - first, while I can query the database and get a list of people within the database, the tagging side of the program will not update the database, not matter what input is passed to it. Second - whenever the program receives any input, the program locks up and the GUI becomes unresponsive.
My code is below, and I am happy for any Questions, Comments, or Criticisms. Yes, the MySQL server is on port '8228'. This code is driving me mad, and I apologize as it may seem messy...
Imports System.IO.Ports
Imports System.Threading
Imports System.Text
Imports System.Data.Odbc
Public Class Form1
Dim WithEvents SerialPort As New IO.Ports.SerialPort
Dim ListStr As String
Dim SQLString As String
Dim fstoday As String = Today.Day.ToString + "_" + Today.Month.ToString + "_" + Today.Year.ToString
Dim NextLine As String
Dim PortNum As String
Dim SqlConn As String
Dim sw As StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs)
Timer1.Start()
SerialPort.ReceivedBytesThreshold = 4
PortNum = "COM6"
SqlConn = "mydomain.local"
Call TestSQLConnectionToolStripMenuItem_Click()
Call ConnectSerial()
'create todays log file
Dim filesys As New FileStream("c:\TagLog\Log-" + fstoday + ".txt", FileMode.Append, FileAccess.Write, FileShare.Write)
filesys.Close()
End Sub
Private Sub ConnectSerial()
'set the USB (COM) Port and Bandwidth (BaudRate)
Try
SerialPort.BaudRate = 115200
SerialPort.PortName = PortNum
SerialPort.Open()
LabPort.Text = "Reader OK"
LabPort.ForeColor = Color.Green
Catch
SerialPort.Close()
LabPort.Text = "Reader Not Found"
LabPort.ForeColor = Color.Red
End Try
End Sub
'This handles setting and reading from the serial port
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim str As String = SerialPort.ReadExisting()
Invoke(myD1, str)
End Sub
'This makes the serial input into String format
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myD1 As New myMethodDelegate(AddressOf myShowStringMethod)
Sub myShowStringMethod(ByVal myString As String)
ListStr = ""
SQLString = ""
'display text to our textbox
TextBox2.AppendText(myString)
'Add the last input to the listbox
ListBox1.Items.Add(TextBox2.Text)
ListStr = ListBox1.Items(ListBox1.Items.Count - 1)
SQLString = "Select * From TagTable where QuickName='" + myString + "';"
Try
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
SQLString = "UPDATE tagtable SET State = NOT State, Time=Now() WHERE QuickName='" + myString + "';"
sw.WriteLine(vbCr + Now() + " " + myString)
Call UpdateSQL()
cn.Close()
Catch ex As Exception
sw.WriteLine(vbCr + Now() + ex.ToString)
End Try
sw.Close()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Once per Tick, check what the COM port is saying.
If SerialPort.IsOpen Then
TextBox2.Text = ""
Else
TextBox2.Text = ""
Call ConnectSerial()
End If
End Sub
Private Function IIf(fileExists As Boolean, p2 As String) As Object
Throw New NotImplementedException
End Function
Private Sub UpdateSQL()
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server and update the records
Dim cmd As OdbcCommand = New OdbcCommand(SQLString, cn)
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
If SQLString <> "" Then
Try
cmd.ExecuteNonQuery()
cn.Close()
LabSQL.ForeColor = Color.Green
Catch ex As Exception
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
sw.WriteLine(vbCr + Now() + " " + ex.ToString)
cn.Close()
End Try
Else
cn.Open()
LabSQL.ForeColor = Color.Green
End If
'If there is a problem, change Sql Label, and clsoe the error'd connection.
cn.Close()
SQLString = ""
End Sub
Private Sub TestSQLConnectionToolStripMenuItem_Click() Handles TestSQLConnectionToolStripMenuItem.Click
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server
Try
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
cn.Close()
'If there is a problem, change Sql Label, display the error in a message box and Close the error'd connection.
Catch ex As OdbcException
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
cn.Close()
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Dim msgans As String
msgans = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Exit?")
If msgans = vbYes Then
SerialPort.Close()
Me.Close()
End If
End Sub
Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
PortNum = "COM1"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
PortNum = "COM2"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
PortNum = "COM3"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
PortNum = "COM4"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click
PortNum = "COM5"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
PortNum = "COM6"
Call ConnectSerial()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Made by Phill C at Epoq IT. Tag Control V2.3")
End Sub
Private Sub LocalMachineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LocalMachineToolStripMenuItem.Click
SqlConn = "localhost"
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub OtherLocationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OtherLocationToolStripMenuItem.Click
SqlConn = InputBox("Enter the SQL Address or Location.", "SQL Location Input", "localhost").ToString
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub ShowUserListToolStripMenuItem_Click() Handles ShowUserListToolStripMenuItem.Click
Dim cn As OdbcConnection
Dim Outstring As String = ""
SQLString = "Select Person,Quickname from TagTable"
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
Dim Query = cmd.ExecuteReader()
Outstring = "FULL NAME, QUICK NAME" + vbCr
While Query.Read
Outstring = Outstring + Query.Item(0) + " , " + Query.Item(1) + vbCr
End While
MsgBox(Outstring)
Query.Close()
cn.Close()
End Sub
Private Sub AddUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the New Users Full Name.", "New User Input", "New User").ToString
Dim QueryQName = InputBox("Enter the New Users Quick Name / Nickname.", "New User Input", "New User").ToString
SQLString = "Insert Into TagTable (QuickName,Person,State,Time) Values ('" + QueryQName + "','" + QueryFull + "','In', NOW());"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("New User has been setup on the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("New User setup has failed, please contact IT Support")
End Try
End Sub
Private Sub DeleteUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the Users Full Name.", "Delete User Input", "User To be deleted").ToString
Dim QueryQName = InputBox("Enter the Users Quick Name / Nickname.", "Delete User Input", "User To be deleted").ToString
SQLString = "Delete From TagTable Where QuickName='" + QueryQName + "' AND Person='" + QueryFull + "';"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("User has been removed from the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("User revomal has failed, please check the full name and quick names, and try again.")
End Try
End Sub
End Class

connecting the log in form in vb.net (adodb.connection usage)

I have this code in log in form, but I don't know the use of adodb.connection, please anyone help me to fix it. I don't know why the word adodb to me has an zigzag error line.
Imports System.Collections.ObjectModel
Imports System.Data
Imports System.Data.SqlClient
Public Class LoginForm1
Dim rs_login As New adodb.Recordset
Dim cn_login As New adodb.Connection
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
rs_login = cn_login.Execute("select * from dbo.studentinfo where [Username] = '" & UsernameTextBox.Text & "' And [Password] = '" & PasswordTextBox.Text & "'")
If rs_login.RecordCount = 0 Then
MsgBox("Invalid Username!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Exit Sub
Else
rs_login = cn_login.Execute("select * from dbo.USERPASS where [Username] = '" & UsernameTextBox.Text & "' And [Password] = '" & PasswordTextBox.Text & "'")
If rs_login.RecordCount = 0 Then
MsgBox("Invalid Username", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Exit Sub
Else
user.Show()
Me.Close()
End If
End If
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
Me.Close()
Home.Show()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SI.Show()
Me.Close()
End Sub
Private Sub LoginForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With cn_login
.CursorLocation = ADODB.CursorLocationEnum.adUseClient
.Provider = "SQLOLEDB.1"
.CommandTimeout = 0
Dim con As New SqlConnection With {.ConnectionString = "Server=Danica-pc; database=SI;user=dandan;pwd=danica;"}
.Open()
End With
End Sub
End Class
You are using a database access code written for VBA. Probably for MS Access. In VB.NET this works very differently. You would use this Imports statement:
Imports System.Data.SqlClient
In VB.NET you would do something like this
Const StandardSecurityConnection As String = _
"Server=Danica-pc;Database=SI;User Id=dandan;Password=danica;"
Const TrustedConnection As String = _
"Server=Danica-pc;Database=SI;Trusted_Connection=True;"
Using conn As New SqlConnection(StandardSecurityConnection) 'Or TrustedConnection
Dim sql As String = _
"SELECT * FROM dbo.studentinfo WHERE Username = #usr AND Password = #pwd"
Using command As New SqlCommand(sql, conn)
command.Parameters.AddWithValue("#usr", UsernameTextBox.Text)
command.Parameters.AddWithValue("#pwd", PasswordTextBox.Text)
conn.Open()
Using dr As SqlDataReader = command.ExecuteReader()
Dim userCol AS Integer = dr.GetOrdinal("Username")
Dim pwdCol AS Integer = dr.GetOrdinal("Password")
While dr.Read()
ConSole.WriteLine("User = {0}, Password = {1}",
dr.GetString(userCol), dr.GetString(pwdCol))
End While
End Using
End Using
End Using

Limiting the time in and time out in a day in VB.NET?

I have developed a time monitoring system using fingerprint where the employee will scan his/her finger then it will record the time in and time out. But my problem is logging in and logging out by the employee is unlimited. Is there a solution where the employee can log in and log out ONCE IN A DAY? Every employee will log in and log out once. Here is my code for my Daily Time Record Form: (Im using visual studio 2010/Digital Persona UareU for my scanner)
Imports MySql.Data.MySqlClient
Imports System.Windows.Forms
Imports DPFP
Public Class frmDTR
Dim counter As Integer = 0
Dim oConn As New MySqlConnection(ConnectionString.ConnString)
Private matcher As DPFP.Verification.Verification
Private matchResult As DPFP.Verification.Verification.Result
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Me.Close()
End Sub
Public Sub SEARCH_EMPLOYEE()
Try
'Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_records WHERE ID_Number='" & strid & "'" 'check tag number if existing
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
With Me
'plot the data into controls
.txtID.Text = reader(1).ToString
.txtFirst.Text = reader(2).ToString
.txtMiddle.Text = reader(3).ToString
.txtLast.Text = reader(4).ToString
.txtAge.Text = reader(5).ToString
.txtBday.Text = reader(6).ToString
.txtDepartment.Text = reader(7).ToString
.txtYear.Text = reader(8).ToString
.txtGender.Text = reader(9).ToString
.txtContact.Text = reader(10).ToString
.txtMobile.Text = reader(11).ToString
.txtEmail.Text = reader(12).ToString
'fetch image from database
Dim imgBytes() As Byte = reader("image") 'image field
Dim image As Bitmap = New Bitmap(New System.IO.MemoryStream(imgBytes)) 'convert binary to image
.ProfilePic.Image = image 'show picture to picture box
End With
Call LOG_EMP() 'look up if login /log out
Timer1.Enabled = True
End While
Else
'Me.lblStatus.Text = "ID not recognized!"
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
Public Sub LOG_EMP()
Try
' Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_logs WHERE ID_Number='" & strid & "' AND Time_Out='Null'"
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
End While
'logout
Call EMP_LOGOUT()
Else
'log in
Call EMPT_LOGIN()
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
'insert login data
Public Sub EMPT_LOGIN()
' Connect to Database
GlobalFunctions.db_connect()
Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
command = New MySqlCommand("INSERT INTO employee_logs values('','" & txtID.Text & "','" & txtFirst.Text & "','" & txtMiddle.Text & "','" & txtLast.Text & "','" & txtDepartment.Text & "','" & Date.Today & "','" & TimeOfDay & "','Null') ", GlobalFunctions.connection, transaction)
command.ExecuteNonQuery()
transaction.Commit()
'sms = txtFirst.Text & " Enter the Building Premises #" & Now 'actual sms
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Welcome!" & txtFirst.Text)
Me.lblStatus.Text = "Successfully Logged IN! Welcome!" 'set status to login
'Will_SendSMS() 'send sms to number
Catch ex As MySqlException
MessageBox.Show("Error in inserting new record! Error: " & ex.Message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
'close connections
GlobalFunctions.connection.Close()
End Sub
Public Sub EMP_LOGOUT()
' Connect to Database
GlobalFunctions.db_connect()
' Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
GlobalFunctions.execute_nonquery("Update employee_logs set Time_Out='" & TimeOfDay & "' WHERE ID_Number='" & strid & "' AND Time_Out='Null' AND Date='" & Date.Today & "'")
transaction.Commit()
'sms = txtFirst.Text & " Left the Building Premises #" & Now & "Powered by: " ' actual sms to be sent
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Goodbye!" & txtFirst.Text)
lblStatus.Text = "Successfully Logged OUT! Goodbye!" ' set status to logout
'Will_SendSMS() 'send sms
Catch ex As MySqlException
MessageBox.Show("Error in updating a record! Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
' close connections
GlobalFunctions.connection.Close()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'counter for display
counter += 1
If counter = 6 Then
Call ClearTextBox(Me)
lblStatus.ForeColor = Color.Lime
Me.lblStatus.Text = "Please scan your finger....."
Lblverify.ForeColor = Color.Black
Lblverify.Text = "Status"
ProfilePic.Image = Nothing
Timer1.Enabled = False
counter = 0
End If
End Sub
Private Sub frmDTR_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
Try
Me.VerificationControl.Focus()
Catch ex As MySqlException
MessageBox.Show("System Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub frmDTR_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
matcher = New Verification.Verification()
matchResult = New Verification.Verification.Result
Me.VerificationControl.Focus()
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Please scan your finger")
End Sub
Private Sub VerificationControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus) Handles VerificationControl.OnComplete
Dim strSQL As String = "Select * from finger_template"
Dim oDa As New MySqlDataAdapter(strSQL, oConn)
Dim dt As New DataTable
Dim dr As DataRow
Try
oDa.Fill(dt)
For Each dr In dt.Rows
Lblverify.ForeColor = Color.Red
Lblverify.Visible = True
Dim bytes As Byte() = Nothing
bytes = dr.Item("byte_template")
Dim tmplate = New DPFP.Template()
tmplate.DeSerialize(bytes)
matcher.Verify(FeatureSet, tmplate, matchResult)
If matchResult.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
strid = dr.Item("Account_ID")
Call SEARCH_EMPLOYEE()
Exit For ' success
End If
If Not matchResult.Verified Then EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
Lblverify.Text = "Status"
lblStatus.Text = "Unrecognize fingerprint....."
Lblverify.ForeColor = Color.Red
lblStatus.ForeColor = Color.Red
Timer1.Start()
Next
Catch ex As Exception
End Try
End Sub
End Class
This is very nice that you are developing this logic. Actually I have come a crossed YOUR question. Now I can recommend you some vb.net code using back end MS ACCESS 2007 .well You just validate when an employee logged in then put this code after log In button or what ever you are using .
Dim cmd1 as oledbcommond
cmd1 = New OleDbCommand("SELECT * FROM LOGTIME WHERE timein<>null and timeout<>null and dt='" & Label8.Text & "' and eid='" & txtemid.Text & "' ", cn)
dr = cmd1.ExecuteReader()
If dr.Read Then
MessageBox.Show("Already this Employee ID contains today's attendance,now you can't Log again", "Information On Your ID", MessageBoxButtons.OK, MessageBoxIcon.Information)
cmd1.Dispose()
cn.Close()
Exit Sub
End If
just follow the steps
Use normal login button which will validate for user
then if the authenticate user then show his login time in another textbox in the same form.and
use one more textbox to show the logout time ,now
1)use two buttons a)button1 as logintime button and b)button2 as logout time button
2)Then write code to add the login time into the data base,and for ur better understanding put one message box too which will shows the"Time in added to the database" and after that put the above code which will validate the current day attendance if the employee wants to login twice or thrice in a day this code will not allow him to login again only once he/she can ... and code the above behind the login button
note:-keep in mind that all the procedure will work after the employee log out ..Hope this will help you out..

What's Causing My If Statement To Be Skipped?

I have an embedded IF statement that should execute following a Database query. However, I noticed at run-time that the entire statement is not being evaluated at all (the one right after While dbData.Read()). What am I doing wrong?
HERE'S THE CODE:
Private Sub ButtonNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonNew.Click
If TextBoxSearch.Text = "" Then
MessageBox.Show("Sorry, you must enter an ACCOUNT# before proceeding!")
TextBoxSearch.Focus()
Else
Try
Dim dbConn As MySqlConnection
dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=parts;Password=parts;Database=accounting")
Dim account As Boolean = True
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
End If
dbConn.Open()
Dim dbQuery As String = "SELECT * FROM customer WHERE accountNumber = '" & TextBoxSearch.Text & "';"
Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbCmd As New MySqlCommand
dbCmd.CommandText = dbQuery
dbCmd.Connection = dbConn
dbAdapter.SelectCommand = dbCmd
dbData = dbCmd.ExecuteReader
While dbData.Read()
If dbData.HasRows Then
'MessageBox.Show("Customer record already exists!")
Call recordExists()
account = False
Call lockForm()
TextBoxSearch.Focus()
Me.Refresh()
Else
'dbData.Close()
account = True
TextBoxAccount.Text = TextBoxSearch.Text
TextBoxAccount.BackColor = Color.LightGray
TextBoxAccount.TabStop = False
Call unlockForm()
TextBoxLastName.Focus()
ButtonSubmit.Visible = True
Me.Refresh()
End If
End While
dbData.Close()
dbCmd.Dispose()
dbAdapter.Dispose()
dbConn.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
End If
End Sub
If dbData.Read() returns False, then it will not enter your loop and therefore the If statement will not be executed. If there are no rows to be read, then Read always returns False, so the If statement is useless where it's at. You need to move that If statement up so that the while loop is inside the If block:
If dbData.HasRows Then
While dbData.Read()
' ...
End While
Else
' ...
End If

set number in button using vb 2008

i have problem in my record database. why when click btnOut. system will save status=1
please anyone help me. to set number in button. this is code, please check if any error. thank.
I'm using vb 2008 and databse mysql
form 1
Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
Const btnIn As Integer = 1
Form1.Show()
End Sub'
Private Sub btnOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOut.Click
Const btnO As Integer = 0
Form1.Show()
End Sub
Form 2
Private Sub btnD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnD.Click
Dim command As MySqlCommand
command = New MySqlCommand
Const btnO As Integer = 0
Const btnI As Integer = 1
command.CommandText = "SEARCH INTO visitor WHERE nokp VALUES ('" & TextBox1.Text & "')"
If TextBox1.Text = "Masukkan No.I/C Anda" Or TextBox1.Text = "" Then
MessageBox.Show("Sila Masukkan No Kad Pengenalan Anda", "Mesej", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
If btnO = 0 Then
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(nok,tkhupd,status)VALUES ('" & TextBox1.Text & "','" & tkhupd & "','" & 1 & "' )"
MessageBox.Show("ok")
command.ExecuteNonQuery()
TextBox1.ResetText()
Else
If btnO = 0 Then
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(nok,tkhupd,status)VALUES ('" & TextBox1.Text & "','" & tkhupd & "','" & 1 & "' )"
MessageBox.Show("ok Out")
command.ExecuteNonQuery()
TextBox1.ResetText()
End If
End If
End If
Exit Sub
End Sub
I hate to say it, but there's just so much wrong in that code. Don't even get me started on the sql injection vulnerabilities (right now, you're just asking to get hacked). No, I'll go even more basic. Look at these two lines from your sample:
Const btnO As Integer = 0
'...
If btnO = 0 Then
'...
Else
'...
End If
btnO is a constant. It can't change. It will always be 0. Therefore, your If/Then check is just play silly: it will always be true. Anything you put in the Else block is worthless: the code can never run.