How to solve this . The process cannot access the file - vb.net

The process cannot access the file 'F:\copy back up\system\HRM 2-5-2013\HRM\HRM\lanbased.txt' because it is being used by another process.
This is my code in sub main
Public localhost As String
Public username As String
Public port As String
Public database As String
Public conn As New MySqlConnection
Public NAME1 As String = "F:\copy back up\system\HRM 2-5-2013\HRM\HRM\lanbased.txt"
Public Sub main()
Dim frm As New Form1
Dim frm1 As New create
If System.IO.File.Exists(NAME1) = True Then
Try
Dim objReader As New System.IO.StreamReader(NAME1)
localhost = objReader.ReadLine() & vbNewLine
username = objReader.ReadLine() & vbNewLine
port = objReader.ReadLine() & vbNewLine
database = objReader.ReadLine() & vbNewLine
conn.ConnectionString = "server=" & Trim(localhost) & ";user id=" & Trim(username) & "; password=" & Trim(port) & "; database=" & Trim(database) & ""
conn.Open()
Application.Run(New Form1())
Catch ex As Exception
MsgBox("Unable to connect to database", vbCritical)
Application.Run(New create())
End Try
End If
Exit Sub
End Sub
and this is my code in my form create.
How do I access the file when it is being used by another process?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim FILE_NAME As String = "F:\copy back up\system\HRM 2-5-2013\HRM\HRM\lanbased.txt"
If TextBox1.Text = Nothing Or TextBox2.Text = Nothing Or TextBox3.Text = Nothing Or TextBox4.Text = Nothing Then
MsgBox("fill up mo pa ngot")
ElseIf System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write(TextBox1.Text + vbCrLf)
objWriter.Write(TextBox2.Text + vbCrLf)
objWriter.Write(TextBox3.Text + vbCrLf)
objWriter.Write(TextBox4.Text + vbCrLf)
objWriter.Close()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ElseIf conn.State = True Then
MsgBox("maka connect naka")
End If
End Sub

first you open your file for reading here :
Dim objReader As New System.IO.StreamReader(NAME1) //1st open
Second you call the form1 : Application.Run(New Form1())
in that Form you have : Dim objWriter As New System.IO.StreamWriter(FILE_NAME) //2nd open
But wait you didn't close your file so you can't open it 2nd time for writing.
So you need to close the file before calling create form 1 like objReader.close()
conn.Open()
objReader.close() <----- this one
Application.Run(New Form1())

Looks like you need to close your streamReader before opening the new form:
objReader.Close()
That will free the file.

Related

vb.net how to create the login permission

Private Sub Edit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Edit.Click
LoginForm.ShowDialog()
If Me.DataGridView1.Rows.Count > 0 Then
If Me.DataGridView1.SelectedRows.Count > 0 Then
Dim intcid1 As Integer = Me.DataGridView1.SelectedRows(0).Cells("ID").Value
'open connection
If Not cn3.State = ConnectionState.Open Then
cn3.Open()
End If
'get data into datatable
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM stock " & _
" WHERE cid=" & intcid1, cn3)
Dim dt As New DataTable
da.Fill(dt)
Me.txtbarcode.Text = intcid1
Me.txtdetail1.Text = dt.Rows(0).Item("CheckerDetail")
Me.txtbarcode.Tag = intcid1
'change button save to update
Me.save.Text = "Update"
'disable button edit
'Me.Edit.Enabled = True
Me.save.Enabled = True
End If
End If
cn3.Close()
End Sub
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
Dim cmd As New OleDb.OleDbCommand
If Not cn3.State = ConnectionState.Open Then
'open connection if it is not open yet
cn3.Open()
End If
cmd.Connection = cn3
cmd.CommandText = "INSERT INTO stock([checkercid],[CheckerName],[ShipQuantity],[Date],[CompanyName],[CheckerDetail]) " &
"VALUES( '" & getLastNumber().ToString & "','" & Me.txtCN.Text & "', '" & Me.txtQty.Text & "', '" & Date.Now.ToString("yyyy-MM-dd HH:mm:ss") & "', '" & Me.txtCompanyN.Text & "', '" & Me.txtdetail1.Text & "')"
'Error message if user not fill yhe textbox
If txtdetail1.Text.Trim = "" Then
MessageBox.Show("Please Insert Data", "Error Message")
Exit Sub
End If
cmd.CommandText = "UPDATE stock " & _
" SET" & _
" [CheckerDetail]='" & Me.txtdetail1.Text & "'" & _
" WHERE [cid]=" & DataGridView1("ID", DataGridView1.CurrentCell.RowIndex).Value
MsgBox("Update Data Successful", MsgBoxStyle.OkOnly, "Message")
cmd.ExecuteNonQuery()
Me.btnClear.PerformClick()
RefreshData1()
cn3.Close()
End Sub
I moved things around trying to keep the User Interface code in the Form and the Data Access code in your class. You had Retries in 2 different places. You only need it in one. boolresetPassword is never used in your code. Since you are hard coding the password don't set a bunch of properties of the class in the form. Just put your connection string in the constructor of the connection in the class. The validated data for the LogIn function is passed to the function.
You don't need all those properties in your class. Just add your connection string. You can pass your Select statement and the connection directly to the constructor of the command. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
I changed the Select to retrieve Count which is all you need to know.
As far as the Cancel button ask a new question with the code for the cancel button.
Public Class LoginForm
Private Retrys As Integer 'Integers automatically initialize to zero
Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
If Retrys = 2 Then
MessageBox.Show("Sorry, you have exceeded the maximum number of attempts to login")
Close()
End If
Dim AppLogin As New ApplicatioLogin
'Do your validation here; not in the Data Access code.
If Not String.IsNullOrWhiteSpace(un.Text) AndAlso Not String.IsNullOrWhiteSpace(pw.Text) Then
If AppLogin.Login(un.Text, pw.Text) Then
SensitiveDataForm.Load()
Close()
Else
Retrys += 1
MessageBox.Show("Login Failed")
End If
Else
MessageBox.Show("Please fill in both username and password")
End If
End Sub
End Class
Public Class ApplicatioLogin
Public Function Login(UserName As String, UserPassword As String) As Boolean
Dim recordCount As Integer
Using cn As New OleDb.OleDbConnection("Your connection string")
Using cmd As New OleDb.OleDbCommand("SELECT Count(*) FROM Users
WHERE UserName = #UserName AND UserPassword = #UserPassword", cn)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = UserName
cmd.Parameters.Add("#UserPassword", OleDbType.VarChar).Value = UserPassword
cn.Open()
recordCount = CInt(cmd.ExecuteScalar)
End Using
End Using
If recordCount = 1 Then
Return True
Else
Return False
End If
End Function
End Class

How to save Received Messages From Gsm Modem to your Mysql Database?

I am trying to save received sms from my modem to MySQL database, and I am using MySQL Workbench for my database.
Here's my functionalities:
1. Auto detect modem
2. Connect modem
3. Send Messages
4. Read Messages
5. Handles (SerialPort Data received)
Here's the Code:1. Auto Detect Modem
'Some Imports
Imports System.Management
Imports System.Threading
Imports System.Text.RegularExpressions
Imports MySql.Data.MySqlClient
Public Class Form1
Dim result() As String
Dim query As String
Dim rcvdata As String = ""
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim ports() As String
ports = Split(ModemsConnected(), "***")
For i As Integer = 0 To ports.Length - 2
ComboBox1.Items.Add(ports(i))
Next
End Sub
Public Function ModemsConnected() As String
Dim modems As String = ""
Try
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_POTSModem")
For Each queryObj As ManagementObject In searcher.Get()
If queryObj("Status") = "OK" Then
modems = modems & (queryObj("AttachedTo") & " - " & queryObj("Description") & "***")
End If
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
Return ""
End Try
Return modems
End Function
'Show Detected or Available modem
Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
Label1.Text = Trim(Mid(ComboBox1.Text, 1, 5))
End Sub
2. Connect/Disconnect Modem
'button connect
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
Try
With SerialPort1
.PortName = Label1.Text
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = True
.ReceivedBytesThreshold = 1
.NewLine = vbCr
.ReadTimeout = 1000
.Open()
End With
If SerialPort1.IsOpen Then
Label3.Visible = True
btnDisconnect.Visible = True
Label3.Text = "Connected - Port " & Label1.Text & " is used"
Else
Label3.Text = "Got some Error, Check your connection with your Modem."
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
'button Disconnect
Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Close()
.Dispose()
Label1.Visible = False
Label3.Visible = False
btnDisconnect.Visible = False
ListView1.Items.Clear()
End With
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
3. Send Messages
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
Dim query As String
Try
Connection()
query = "INSERT INTO thesis.tblsentitems (PhoneNumber, message) VALUES('" & txtNumber.Text & "', '" & txtMessage.Text & "')"
sqlcmd = New MySqlCommand(query, conn)
sqlreader = sqlcmd.ExecuteReader
With SerialPort1
.Write("at" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgf=1" & vbCrLf)
Threading.Thread.Sleep(200)
.Write("at+cmgs=" & Chr(34) & txtNumber.Text & Chr(34) & vbCrLf)
.Write(txtMessage.Text & Chr(26))
Threading.Thread.Sleep(200)
End With
If rcvdata.ToString.Contains(">") Then
MsgBox("Message Succesfully Sent")
conn.Close()
Else
MsgBox("Got some error!")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Text Messaging")
End Try
End Sub
4. Read Messages
Private Sub btnReadsms_Click(sender As System.Object, e As System.EventArgs) Handles btnReadsms.Click
Try
With SerialPort1
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CPMS=""SM""" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("AT+CMGL=""ALL""" & vbCrLf)
Threading.Thread.Sleep(1000)
'MsgBox(rcvdata.ToString)
readmsg()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Save Received message to ListView1
Private Sub readmsg()
Try
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
lineoftext = rcvdata.ToString
arytextfile = Split(lineoftext, "+CMGL", , CompareMethod.Text)
For i = 1 To UBound(arytextfile)
Dim input As String = arytextfile(i)
Dim pattern As String = "(:)|(,"")|("","")"
result = Regex.Split(input, pattern)
Dim concat() As String
With ListView1.Items.Add("null")
'for index
.SubItems.AddRange(New String() {result(2).ToString})
'for status
.SubItems.AddRange(New String() {result(4).ToString})
'for number
Dim my_string, position As String
my_string = result(6)
position = my_string.Length - 2
my_string = my_string.Remove(position, 2)
.SubItems.Add(my_string)
'for date and time
concat = New String() {result(8)}
.SubItems.AddRange(concat)
'for message
Dim lineoftexts As String
Dim arytextfiles() As String
lineoftexts = arytextfile(i)
arytextfiles = Split(lineoftexts, "+32", , CompareMethod.Text)
.SubItems.Add(arytextfiles(1))
End With
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
5. Handles (SerialPort Data received)
Private Sub SerialPort1_datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim datain As String = ""
Dim numbytes As Integer = SerialPort1.BytesToRead
For i As Integer = 1 To numbytes
datain &= Chr(SerialPort1.ReadChar)
Next
test(datain)
End Sub
Private Sub test(ByVal indata As String)
rcvdata &= indata
End Sub
Hope someone can Help, please... :/

How to Refresh. Datagridview after adding data.im using sql database

below is my code for my project.
hope you can help me.
thanks in advance. :)
this is my sqlcontrol code
Imports System.Data
Imports System.Data.SqlClient
Public Class SQLControl
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=xxx\SQLEXPRESS;Database=SQLTest;User=sa;Pwd=xxxx;"}
Public SQLCmd As SqlCommand 'allow us to fire query at the data base
Public SQLDA As SqlDataAdapter
Public SQLDataset As DataSet
Public dtable As New DataTable
Public bs As New BindingSource
'QUERY PARAMETERS
Public Params As New List(Of SqlParameter)
Public RecordCount As Integer
Public Exception As String
Public Function HasConnection() As Boolean
Try
SQLCon.Open()
SQLCon.Close()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub ExecQuery(ByVal Query As String)
Try
SQLCon.Open()
'CREATE SQL COMMAND
SQLCmd = New SqlCommand(Query, SQLCon)
'LOAD PARAMETER INTO SQL COMMAND
Params.ForEach(Sub(x) SQLCmd.Parameters.Add(x))
'CLEAR PARAMETER LIST
Params.Clear()
'EXCUTE COMMAND FILL MY DATASET
SQLDataset = New DataSet
'EXCUTE COMMAND WIHTOUT ADAPTER
SQLDA = New SqlDataAdapter(SQLCmd)
RecordCount = SQLDA.Fill(SQLDataset)
SQLCon.Close()
Catch ex As Exception
Exception = ex.Message
End Try
If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
End Sub
Public Sub RunQuery(ByVal Query As String)
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
'LOAD SQL RECORDS FOR DATAGRID
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDataset = New DataSet
SQLDA.Fill(SQLDataset)
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
End Sub
Public Sub AddMember(ByVal PC As String, ByVal IP As String, ByVal Name As String, ByVal Email As String, ByVal Department As String, ByVal Location As String,
ByVal Model As String, ByVal Specs As String, ByVal Dt As String, ByVal Asset As String, ByVal Rent As String)
Try
Dim strInsert As String = "INSERT INTO MEMBERS (pc,ip,name,email,department,location,model,specs,date,asset,rent) " & _
"VALUES (" & _
"'" & PC & "'," & _
"'" & IP & "'," & _
"'" & Name & "'," & _
"'" & Email & "'," & _
"'" & Department & "'," & _
"'" & Location & "'," & _
"'" & Model & "'," & _
"'" & Specs & "'," & _
"'" & Dt & "'," & _
"'" & Asset & "'," & _
"'" & Rent & "')"
MsgBox(strInsert)
SQLCon.Open()
SQLCmd = New SqlCommand(strInsert, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
And this is my form code:
Public Class Form1
Private SQL As New SQLControl
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'EXECUTE QUERY AND POPULATE GRID
SQL.ExecQuery("SELECT * FROM members")
LoadGrid()
'DISABLE SAVE BUTTON
cmdSave.Enabled = False
End Sub
Private Sub LoadGrid()
'IF OUR DATA IS RETURNED AND POPULATE GRID & BUILD UPDATE COMMAND
If SQL.RecordCount > 0 Then
dgvData.DataSource = SQL.SQLDataset.Tables(0)
dgvData.Rows(0).Selected = True
SQL.SQLDA.UpdateCommand = New SqlClient.SqlCommandBuilder(SQL.SQLDA).GetUpdateCommand
End If
End Sub
Private Sub dgvData_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellValueChanged
cmdSave.Enabled = True
End Sub
Private Sub dgvData_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles dgvData.RowsRemoved
cmdSave.Enabled = True
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
'SAVE UPDATE TO THE DATA BASE
Try
SQL.SQLDA.Update(SQL.SQLDataset) ' TO DO: DATA VALIDATION
Catch ex As Exception
MsgBox("Already Exists")
End Try
'REFRESH GRID DATA
LoadGrid()
'DISABLE SAVE BUTTON
cmdSave.Enabled = False
End Sub
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
If Trim(txtPC.Text) = "" Then
MsgBox("Please fill out the pc name.")
Exit Sub
End If
If Trim(txtIP.Text) = "" Then
MsgBox("Please fill out the ip address.")
Exit Sub
End If
'Query for user
SQL.RunQuery("SELECT * FROM members WHERE members.PC = '" & txtPC.Text & "'")
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
MsgBox("The name that you have enter enter is already exists")
Exit Sub
End If
SQL.RunQuery("SELECT * FROM members WHERE members.IP = '" & txtIP.Text & "'")
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
MsgBox("The IP Address that you have enter is already exists!")
Exit Sub
End If
SQL.RunQuery("SELECT * FROM members WHERE members.Asset = '" & txtAsset.Text & "'")
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
MsgBox("The Asset that you have enter is already exists")
Exit Sub
Else
CreateUser()
txtPC.Clear()
txtIP.Clear()
txtName.Clear()
txtEmail.Clear()
txtDepartment.Clear()
txtLocation.Clear()
txtModel.Clear()
txtSpecs.Clear()
txtDt.Clear()
txtAsset.Clear()
txtRent.Clear()
End If
End Sub
Public Sub CreateUser()
SQL.AddMember(txtPC.Text, txtIP.Text, txtName.Text, txtEmail.Text, txtDepartment.Text,
txtLocation.Text, txtModel.Text, txtSpecs.Text, txtDt.Text, txtAsset.Text, txtRent.Text)
End Sub
End Class
I don't know how to refresh the datagridview
this will works. just
Copy And Paste this to your load form.
Public Sub RefreshUserGrid()
' RUN QUERY
SQL.ExecQuery("SELECT * FROM members")
If SQL.SQLDataset.Tables.Count > 0 Then
dgvData.DataSource = SQL.SQLDataset.Tables(0)
dgvData.Rows(0).Selected = True
End If
End Sub
and also copy and paste this RefreshUserGrid() at your add command.

Read String From Serial port Visual Basic

Imports System.IO.Ports
Imports System.Text
Public Class Form4
Dim myStringBuilder As String
Dim insert As New OleDb.OleDbCommand
Dim cnn As New OleDb.OleDbConnection
Public user As String
Private Sub Serialport2_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
myStringBuilder = SerialPort2.ReadExisting()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
Private Sub UpdateControls(ByVal sender As Object, ByVal e As EventArgs)
Dim A As String = myStringBuilder
Dim Sqql As String
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
insert.Connection = cnn
Dim dt As New DataTable
Sqql = "SELECT * FROM `FileInfo` WHERE `File ID`='" & A & "'"
Dim cmd As New OleDb.OleDbDataAdapter(Sqql, cnn)
cmd.Fill(dt)
Dim i As Integer = dt.Rows.Count
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
If i = 1 Then
insert.CommandText = "INSERT INTO `File Log`(File ID,Name,Information,Time,Date) " & _
" VALUES('" & A & "','" & dt.Rows(0).Item("Name") & "','" & user & " telah" & dt.Rows(0).Item("Status") & "File" & "','" &
_
TimeOfDay & "','" & todaysdate & "')"
textBox1.Text += dt.Rows(0).Item("Name") & " " & TimeOfDay & " " & todaysdate &
Environment.NewLine
textBox1.Select(textBox1.TextLength, 0)
textBox1.ScrollToCaret()
insert.ExecuteNonQuery()
myStringBuilder = ""
Else
myStringBuilder = ""
textBox1.Text += A & Environment.NewLine
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
If SerialPort2 IsNot Nothing Then
SerialPort2.Close()
End If
SerialPort2 = My.Computer.Ports.OpenSerialPort("COM27", 9600, Parity.None, 8, StopBits.One)
textBox1.Text = "-- Door Have Open -- " & Environment.NewLine & Environment.NewLine
End Sub
Private Sub textBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textBox1.TextChanged
End Sub End Class
in my serial monitor view it will appear correctly but in visual basic it will auto break line and not display the string in one line.
I Tried other method like serialport.readline() but nothing happen.
If you are having issues with extracting data from your serial port you could try this:
Sub SerialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Dim currentSP As SerialPort = Convert.ChangeType(sender, GetType(SerialPort))
Dim strBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
For index = 1 To currentSP.BytesToRead
strBuilder.Append(Convert.ChangeType(currentSP.ReadByte(), GetType(Char)))
Next
' Have a global string to allow the threads to have a shared resource
myString = strBuilder.ToString()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
It should work the same way as the SerialPort.ReadLine(), this approach also lets you manipulate the data however you want. Instead of working with a string you could always work the data like this:
Dim buffer As Byte() = New Byte(currentSP.BytesToRead) {}
buffer(index) = Convert.ChangeType(currentSP.ReadByte(), GetType(Byte))
So instead of appending the Char to the String you can add the Byte to the buffer
Dim str As String = MyCOMPort.ReadExisting()
If Me.InvokeRequired Then
Me.Invoke(New dlUpdateText(AddressOf updatetext), str)
Else
updatetext(str)
End If

login form using ms access in vb.net

I'm creating a login form for vb.net using ms access 2003 as database. But it only checks for the username and bypasses the password. Meaning that if the username is correct and the password doesn't jive with the username, the user can still enter the system. Here is my code:
Try
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from admintable where AdminName= '" & TextBox4.Text & "' ", cn)
cn.Open()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("AdminName")
NoPas = rdr("AdminPass")
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
adminview.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox4.Clear()
TextBox3.Clear()
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
How do I do it so that it checks both username and password?
You are using a single line IF .. THEN :
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
so the next line will always be executed:
adminview.Show()
you have to rearrange your IF .. THEN conditions
I will share about login system in vb.net using binding navigator that less of coding. just following the link below!
http://www.tesear.com/2011/09/login-system-in-vbnet.html
You could have BOTH the uname and pword in the database and "WHERE" on both, if you get no record back, then you have your answer.
Try using System.String.Compare(String str1,String str2, Boolean ) As Integer like:
If (System.String.Compare(TextBox4.Text, NoAcc, false) And System.String.Compare(TextBox3.Text, NoPas, false)) Then NoAccmod2 = NoAcc
here is the code:
Imports System.Data
Imports System.Data.OleDb
Public Class Form5
Inherits System.Windows.Forms.Form
Dim mypath = Application.StartupPath & "\login.mdb"
Dim mypassword = ""
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Dim sql = "SELECT UserID ,PassID FROM MYTAB WHERE USERID='" & TextBox1.Text & "' AND PASSID='" & TextBox2.Text & "'"
cmd = New OleDbCommand(sql, conn)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MessageBox.Show("Authentication failed...")
Me.Show()
Else
MessageBox.Show("Login successfully...")
Dim frmDialogue As New Form11
frmDialogue.ShowDialog()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Close()
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.Hide()
Dim frmDialogue As New Form1
frmDialogue.ShowDialog()
End Sub
Private Sub Form5_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim frm As New Form1
frm.Show()
End Sub
End Class
Try
Dim NoAcc As String
Dim NoPas As String
Dim rdr As OleDbDataReader
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\mobilestore.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from logindata where Username= '" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", cnn)
'NoAcc = TextBox1.Text
'NoPas = TextBox2.Text
cnn.Open()
rdr = cmd.ExecuteReader
If (rdr.Read()) Then
NoAcc = rdr("Username")
NoPas = rdr("password")
If (TextBox1.Text = NoAcc And TextBox2.Text = NoPas) Then
Adminpage.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
End Sub