How can I check a received string for a specific word? - vb.net

I am sending the string "end" from my arduino uno to a vb.net application. I want the vb.net app to recognise the word and conduct a specific action. I can see that the word is being received in the console, but it doesn't seem to be recognised by the code.
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Console.WriteLine(SerialPort1.ReadExisting)
If SerialPort1.ReadExisting IsNot "end" Then
dataRxd = dataRxd & SerialPort1.ReadExisting
Else
txtRx.Text &= dataRxd
Console.WriteLine("###############")
Console.WriteLine(dataRxd)
'Dim result As newData = JsonConvert.DeserializeObject(Of newData)(dataRxd)
'Dim com As result.com
'SerialPort1.Close()
'MySqlConn = New MySqlConnection
'MySqlConn.ConnectionString = "server=localhost;userid=root;password=g4rg45m3ll1;database=tags"
'Try
' Dim SDA As New MySqlDataAdapter
' Dim dbDataSet As New DataTable
' Dim bSource As New BindingSource
' MySqlConn.Open()
' 'Query = "update tags.tags_read set LastRead= now() where TagID='" & dataRxd & "';"
' Query = "insert into tags.tags_read values ('" & dataRxd & "', now());"
' cmd = New MySqlCommand(Query, MySqlConn)
' reader = cmd.ExecuteReader
'Catch ex As MySqlException
' MessageBox.Show(ex.Message)
'End Try
'MySqlConn.Dispose()
'MySqlConn.Close()
'SerialPort1.Open()
End If
End Sub
Here is a sample of the received data to the vb.net app, showing that the word is being received:
0001220000570221001B
end
0001220000570221001B
end
The thread 0x4a70 has exited with code 0 (0x0).

ReadExisting is a method, not a property. If you call it once then you are reading the existing data, so there's no more data. You can't call it again and get the same data. If you expect to use the data that you read more than once then do as should always be the case: assign the method result to a variable and then use that variable as required.
Dim msg = SerialPort1.ReadExisting()
Console.WriteLine(msg)
If msg <> "end" Then
dataRxd = dataRxd & msg
Note that I also used <> rather than IsNot, because it's really value equality and not reference equality that you care about.

Related

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

What data type to use on Combo Box in Try-catch statement vb.net?

Have a look at the code below. This code works on all the textboxes except on the combobox. I guess it is because of the data type. Is there a way to fix it. Please do help me. Thank You!
Dim int As Integer
Dim str As String
Try
int = CInt(txtsid.Text) & CInt(txtsph.Text)
str = CStr(txtsfn.Text) & CStr(txtsln.Text) & CStr(txtint.Text) & CStr(txtsem.Text) & CStr(cbogen.Text)
Catch ex As Exception
MessageBox.Show("Please Type Informations Properly")
Return
End Try
Dim result As Integer = MessageBox.Show("Are you sure you want to proceed?", "Proceed", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
UserHomepage.Show()
Me.Hide()
cmdInsert.CommandText = "Insert into student Values(" + txtsid.Text + ",'" + txtint.Text + "','" + txtsfn.Text + "','" + txtsln.Text + "', '" + cbogen.Text + "', " + txtsph.Text + ", '" + txtsem.Text + "');"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.ExecuteNonQuery()
ElseIf result = DialogResult.No Then
Me.Show()
UserHomepage.Hide()
End If
Comment and explanations in line.
Private Sub UpdateDatabase()
'This entire are of code down to the End Try does nothing
'Any .Text property is already a String and does not need CStr
'In the int = line you have 2 Strings that you convert to Integers, Then they must
'be changed back to Strings in order to concatenate them, Then the new string is again changed to an
'integer!! Argh!
'Dim int As Integer
'Dim str As String
'Try
' int = CInt(txtsid.Text) & CInt(txtsph.Text)
' str = CStr(txtsfn.Text) & CStr(txtsln.Text) & CStr(txtint.Text) & CStr(txtsem.Text) & CStr(cbogen.Text)
'Catch ex As Exception
' MessageBox.Show("Please Type Informations Properly")
' Return
'End Try
'Changed Integer to DialogResult
Dim result As DialogResult = MessageBox.Show("Are you sure you want to proceed?", "Proceed", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
UserHomepage.Show()
Me.Hide()
Try 'This is the place for Try...End Try. Networks and database connections can have
'all sorts of unexpected errors.
'The Using blocks ensure that your objects are closed and disposed even if there is an error.
'Keep your connections local
Using cnnOLEDB As New OleDbConnection("Your connection string")
'Pass your command text and the connection to the constructor of the command
Using cmdInsert As New OleDbCommand("Insert into student Values(?,?,?,?,?, ?,?);", cnnOLEDB)
cmdInsert.CommandType = CommandType.Text
'USE PARAMETERS to avoid SQL injection
'If this first parameter is an autonumber field, it should be removed
'from the Insert statement. Also remove a "?" You may have to list the
'fields in the first part of the Insert to match the question marks.
cmdInsert.Parameters.Add("#sid", OleDbType.Integer).Value = txtsid.Text
cmdInsert.Parameters.Add("#int", OleDbType.VarChar).Value = txtint.Text
cmdInsert.Parameters.Add("#sfn", OleDbType.VarChar).Value = txtsfn.Text
cmdInsert.Parameters.Add("#sln", OleDbType.VarChar).Value = txtsln.Text
cmdInsert.Parameters.Add("#gen", OleDbType.VarChar).Value = cbogen.Text
cmdInsert.Parameters.Add("#sph", OleDbType.Integer).Value = txtsph.Text
cmdInsert.Parameters.Add("#sem", OleDbType.VarChar).Value = txtsem.Text
cnnOLEDB.Open()
cmdInsert.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'The following ElseIf is useless
'Me is already visible and UserHomepage is not
'ElseIf result = DialogResult.No Then
' Me.Show()
' UserHomepage.Hide()
End If
End Sub
'Do your validation here
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
'For a string field
If TextBox1.Text = "" Then
MessageBox.Show("Required field")
e.Cancel = True
TextBox1.Select(0, TextBox1.Text.Length)
End If
'Or
'For a number field
Dim myInt As Integer
If Not Int32.TryParse(TextBox1.Text, myInt) Then
MessageBox.Show("Requires number")
e.Cancel = True
TextBox1.Select(0, TextBox1.Text.Length)
End If
End Sub

An unhandled exception of tpe 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
The above unhandled exception shows when i run below code :
Private Sub chUser()
conn = New SqlConnection(conStr)
conn.Open()
myConn.clName = clNameDGV.SelectedRows.Item(0).Cells(0).Value //EXCEPTION SHOWS FOR THIS LINE
Dim comStr As String = "Select Count(*) from Login_Detail Where Clinic_Name = '" & clNameDGV.SelectedRows.Item(0).Cells(0).Value & "'"
Dim comm As New SqlCommand(comStr, conn)
Dim i As Integer = comm.ExecuteScalar()
If i = 0 Then
If MessageBox.Show("No User Information found for '" + clNameDGV.SelectedRows.Item(0).Cells(0).Value + "'." + vbNewLine + "Do you want to enter new user details ?", "No Users Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
Dim nf As New CreateUser
nf.TopMost = True
nf.ShowDialog(Me)
End If
End If
Dim nf1 As New LoginForm
nf1.TopMost = True
nf1.ShowDialog(Me)
conn.Close()
End Sub
I have only one column with multiple rows in my datagridview. I run above function on doubleclick event of datagridview.
As you have a one-column DGV, you only need to use the .SelectedCells property, and you should check that only one cell is selected, something like this:
Private Sub ChUser()
If clNameDGV.SelectedCells.Count <> 1 Then
' not exactly one row was selected
Exit Sub
End If
Dim clinicName As String = CStr(clNameDGV.SelectedCells.Item(0).Value)
Dim nFoundRecords As Integer
Dim conn As SqlConnection = Nothing
Try
conn = New SqlConnection(conStr)
conn.Open()
myConn.clName = clinicName
Dim sql As String = "SELECT COUNT(*) FROM Login_Detail WHERE Clinic_Name = #ClinicName"
Using cmd As New SqlCommand(sql, conn)
'TODO: Set the .SqlDbType parameter correctly.
'TODO: Add the .Size parameter to match the setting in the database.
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#ClinicName", .SqlDbType = SqlDbType.NVarChar, .Value = clinicName})
nFoundRecords = CInt(cmd.ExecuteScalar())
End Using
conn.Close()
Finally
If conn IsNot Nothing Then
conn.Dispose()
End If
End Try
If nFoundRecords = 0 Then
Dim message As String = "No User Information found for '" & clinicName & "'." & vbNewLine & "Do you want to enter new user details?"
Dim userChoice As DialogResult = MessageBox.Show(message, "No Users Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If userChoice = DialogResult.OK Then
Dim nf As New CreateUser
nf.TopMost = True
nf.ShowDialog(Me)
End If
End If
Dim nf1 As New LoginForm
nf1.TopMost = True
nf1.ShowDialog(Me)
End Sub
Please note how I have used CStr and CInt in appropriate places. If you use Option Strict On then it will point out for you where you should make explicit conversions (among other things). Also, I split up some lines into several lines to make it easier to read, and hence easier to edit.

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

VB.NET RowUpdating event doesn't work

The following code runs successfully with no errors, but I still don't get the new data from the grid, by adding a break point, and stepping forward, the data in the variables are the original data, not the updated data, what am I missing?
Private Sub grvSample_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles grvSample.RowUpdating
Dim row As GridViewRow = DirectCast(grvSample.Rows(e.RowIndex), GridViewRow)
Dim passportNumber As TextBox = DirectCast(row.FindControl("txtNumber"), TextBox)
Dim expiry As TextBox = DirectCast(row.FindControl("txtExpiry"), TextBox)
Dim type As TextBox = DirectCast(row.FindControl("txtType"), TextBox)
Dim name As TextBox = DirectCast(row.FindControl("txtName"), TextBox)
Dim cinvnum As TextBox = DirectCast(row.FindControl("txtCINVNUM"), TextBox)
Dim last As TextBox = DirectCast(row.FindControl("txtLast"), TextBox)
Dim drplist As DropDownList = DirectCast(row.FindControl("DDLNat"), DropDownList)
Dim Conn As New SqlConnection("Data Source=ADMIN-PC;Initial Catalog=T1INV;Integrated Security=True")
Dim cmd As New SqlCommand("update pass_details set passnat='" & drplist.SelectedValue & "', passno='" & passportNumber.Text.Trim() & "', passexp='" & expiry.Text.Trim() & "', passtype='" & type.Text.Trim() & "', nameonpass='" & name.Text.Trim() & "', namelast='" & last.Text.Trim & "' where cinvnum='" & cinvnum.Text.Trim() & "'", Conn) ' where cinvnum='" & grvSample.Rows(e.RowIndex) & "'")
Try
Conn.Open()
cmd.ExecuteNonQuery()
' Refresh the data
grvSample.EditIndex = -1
Dim SSQL = "select * from pass_details"
Dim ds As New DataSet("GET_HIS")
Dim adp As New SqlDataAdapter(SSQL, Conn)
adp.Fill(ds, "TAB_SMT")
grvSample.DataSource = ds.Tables("TAB_SMT")
grvSample.DataBind()
Catch ee As SqlException
Finally
cmd.Dispose()
Conn.Close()
Conn.Dispose()
End Try
End Sub
I assume that you're databinding the GridView also on postbacks. That would override the changed values.
So check it in Page_Load in the following way:
If Not Page.IsPostBack Then
BindGrid()
End If
Apart from that GridViewUpdateEventArgs contains a dictionary with NewNalues.
Dim passportNumber = e.NewValues("passno")
Note that they're also overridden on databind.