display number of rows found from data table in listview - mysql

I am trying to display the number of rows in a listview. I tried this code but instead of working, it throws the error below. I am using mysql for a back end:
error:
System.InvalidCastException: Conversion from string " '" to type
'Double' is not valid. ---> System.FormatException: Input string was
not in a correct format
VB Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
ViewState("Data") = ""
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM school")
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
cmd.CommandTimeout = 0
Using dt As New DataTable()
sda.Fill(dt)
ViewState("Data") = dt
schoollists.DataSource = dt
schoollists.DataBind()
End Using
End Using
End Using
End Using
countResult.Text = (" '" + schoollists.Items.Count + "';")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub

In VB.NET using the + Operator to concatenate a string and a number yields unexpected results (or better an exception as you can see)
Using + between a string and a number results in the attempt to convert the string " '" (in your case) to a number and, of course, this will fail.
To be on the safe side, the correct operator to concatenate strings in VB.NET is the & operator
countResult.Text = (" '" & schoollists.Items.Count & "';")
As a side note, this will happen because you have, in your project settings, the OPTION STRICT set to OFF. With this configuration the compiler cannot catch this problem and you cannot see the error until you hit it at runtime. I strongly suggest to set OPTION STRICT to ON also if, initially, you will have a lot of code to fix.
A detailed explanation of the behavior of the plus operator when used with numbers and strings is present in the REMARKS section of the + Operator on MSDN

Related

HOW TO USE UPDATE IN SQL WITH VB

Can you please help me, what the problem of my code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'UPDATE Data
openCon()
Try
cmd.Connection = con
cmd.CommandText = "UPDATE emp_table SET FNAME = '" & TextBox1.Text & "', LNAME= '" & TextBox2.Text & "', AGE = '" & TextBox3.Text & "', GENDER ='" & Gender & "', OFFICE STAFF= '" & ComboBox1.Text & "' Where ID ='" & TxtID.Text & "' "
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
There are many problems in your code and if you look around this site I think you will find many partial answers that step by step will help you solve your problems. So I try to give you an answer where all the problems are examined, discussed and solved.
First problem: How do you handle the connection.
It seems that you have a global connection instance called con that you open with openCon. This is not a good approach and always a source of problems. You always need to check if the connection is closed properly or not. For example, in the code above you have forgot to close the connection in case of exception and this will lead to other exceptions in some code not related to this one. You keep resources on the server locked to you and this will decrease the performance of every one connection to that server.
I would change your openCon to this
Public Function openCon() as MySqlConnection
Dim con as MySqlConnection = new MySqlConnection(....here connection string ...)
con.Open()
return con
End Function
This will create a new instance of the MySqlConnection every time you call this method Now you can remove the global connection instance and use the one returned by openCon in this way
Using con As MySqlConnection = openCon()
.... code that use the local con object
End Using
This will close and destroy the connection even if an exception occurs inside the Using block and the ADO.NET libraries are smart enough to use a thing called Connection Pooling to reduce the time required to build and open a connection with the same connection string.
Second problem: The syntax error.
Looking at the point of the error suggested by the message I can see a field name composed by two words separated by a space. This is fine, but then you should remember that the sql parser cannot understand this and you need to help it enclosing the two words in a backtick character (ALT+096) so the parser understand that this is a single field name. Given the fact column names are an internal information of no concern for your end user then why use spaces in column names? If possible remove the space in column names.
Third problem: Sql Injection and other syntax errors
You are concatenating strings to build an sql command. But this is an easy target for wannabe hackers. Suppose that I write in your textBox1 this string instead of a First Name: Mario'; --
Then your command becomes
UPDATE emp_table SET FNAME = 'Mario'; -- xxxxxxxxxxxx
everything after -- is considered a comment and the query is still executable, but it changes every record in emp_table to have a first name equal to Mario.
But the query could fail as well if someone writes a Last Name that contains an apostrophe like O'Leary just now the query is no more syntactically valid.
The solution to this is always one. Use Parameters.
Recap of changes to your code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim cmdText as String = "UPDATE emp_table SET FNAME = #fname,
LNAME= #lname, AGE = #age, GENDER =#gender,
`OFFICE STAFF` = #staff
Where ID =#id"
Using con as MySqlConnection = openCon()
Using cmd as MySqlCommand = new MySqlCommand(cmdText, con)
Try
cmd.Parameters.Add("#fname", MySqlDbType.VarChar).Value = textBox1.Text
cmd.Parameters.Add("#lname", MySqlDbType.VarChar).Value = textBox2.Text
cmd.Parameters.Add("#age", MySqlDbType.VarChar).Value = textBox3.Text
cmd.Parameters.Add("#gender", MySqlDbType.VarChar).Value = gender
cmd.Parameters.Add("#staff", MySqlDbType.VarChar).Value = combobox1.Text
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = txtID.Text
cmd.ExecuteNonQuery()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Using
End Sub
In the recap I have added parameters for every single field that you want to update. But remember. Parameters should have a Type (The MySqlDbType here) that should match the type of the field and the value should be of the same type. For example it seems improbable that Age is a varchar field. So you should convert TextBox3.Text to an integer if the field is an integer.

Object reference not set to an instance of an object Mysql VB.net

I'm trying to join tables and load data with a specific value from a Textbox but It's giving the following error:
"An exception of type 'System.NullReferenceException' occurred in Boxing.exe but was not handled in user code
Additional information: Object reference not set to an instance of an object."
My code:
Dim Joinloin As New MySqlCommand("SELECT boxno, specie, netweight, producttype, loin FROM loins, boxing WHERE loins.code = boxing.loin AND type = '" & Label9.text & "' ORDER BY loincode", conn.getConnection)
I tried to run without the "type = '" & Label9.text & "'" and works perfectly.
Because "Type" is a reserved word in SQL, you need to change it in your SQL Database and in your Query to something like "TypeX" and try again.
Connections and Commands need to have their Dispose methods called so they can release unmanaged resources. To do this they should be declared in the method they are are used. Using...End Using blocks handle the declare, and Close/Dispose.
Don not concatenate strings to build sq statements. Always use parameters.
Your join syntax went out with the last milenium. I made wild guesse about which field belonged to which table. Is there really a field called loincode?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt = GetProductData(Label9.Text)
'Do something with the data table
End Sub
Private Function GetProductData(type As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection("You connection string"),
cmd As New MySqlCommand("SELECT boxing.boxno, loins.specie, boxing.netweight, loins.producttype, boxing.loin
FROM boxing
JOIN loins ON boxing.loin = loins.code Where loins.[type] = #Type
ORDER BY boxing.loincode", cn)
cmd.Parameters.AddWithValue("#Type", type)
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function

Why won't my .net application accept the SQL Query via user input?

I'm currently writing a quick .net program that will allow users to query a Database
I've got it working to a point where it'll run SELECT statements that are hardcoded but when I get the "sql" variable to look at the contents in a text box (user input) it chucks up an error. This happens even when I copy and paste a SQL Query that works hardcoded into the user text box
This is my code:
Imports MySql.Data.MySqlClient
Public Class form_queueDepth
Public dbconn As New MySqlConnection
Public sql As String
Public dbread As MySqlDataReader
Public dbcomm As MySqlCommand
Private Sub form_queueDepth_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbconn = New MySqlConnection("Data Source=10.232.7.41;user id=Alex;password=abc;database=alexvb")
Try
dbconn.Open()
MsgBox("Succeed")
Catch ex As Exception
MsgBox("Unable to connect: " & ex.Message.ToString)
End Try
End Sub
Private Sub button_ExecuteQuery_Click(sender As Object, e As EventArgs) Handles button_ExecuteQuery.Click
sql = "SELECT * FROM depth_store WHERE ID < '10';"
dbcomm = New MySqlCommand(sql, dbconn)
MsgBox(sql)
Try
dbread = dbcomm.ExecuteReader()
While dbread.Read
listBox_QueryResults.Items.Add(dbread("Queue_Manager").ToString() & " | " & dbread("Queue").ToString() & " | " & dbread("DTime").ToString() & " " & dbread("QueueDepth").ToString())
End While
MsgBox("Success")
Catch ex As Exception
MsgBox("Error: " & ex.Message.ToString)
End Try
End Sub
End Class
SO the above code will work but the moment i change "sql = "SELECT * FROM depth_store WHERE ID < '10';" to "sql = (textBox_UserQuery).ToString" and then copy & paste the query It chucks up an error stating:
http://i66.tinypic.com/2pqnxmo.png
Any suggestions/help would be much appreciated - Let me know if any you require any other information
textBox_UserQuery is the name of an instance of a TextBox.
The ToString() method returns the name of the class
IE: System.Windows.Forms.TextBox.
If you want to use the content of a TextBox you need the property Text.
sql = textBox_UserQuery.Text
Said that, I hope that this 'program' is only for your internal use. If not you are giving away the capability to destroy an entire database. (DELETE FROM .....)

MySQL Data NOT Deleting from table VB.NET

Why won't this delete the data in my MySQL database!?
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Try
dbCon = New MySqlConnection("Server=Localhost;Database=myusers;Uid=root;Pwd=Mypassword")
strQuery = "DELETE settings FROM settings WHERE user=" & Me.loginuser.Text
'* FROM settings WHERE user = "Testuser"'
SQLCmd = New MySqlCommand(strQuery, dbCon)
' OPEN THE DB AND KICKOFF THE QUERY
dbCon.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
req1.Text = "" And exlink.Text = ""
End While
' DONE! Close DB
DR.Close()
dbCon.Close()
Catch ex As Exception
TextBox8.Text = ("Fail" & vbCrLf & vbCrLf & ex.Message)
End Try
Here is a picture of my database:
Alternatively I could somehow make it replace what is already in the database, in which case please help me with that.
Try
strQuery = "DELETE FROM settings " _
& " WHERE user = '" & Me.loginuser.Text & "'"
but as was stated earlier, you should be using parameterized queries. If you had a user named O'Brien then your query (as composed above) would fail because of the embedded single quote. When you use DELETE, you are deleting entire records and you already specify the table name in the FROM clause.
I will try to change your code in this way
Using con = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText = "DELETE * FROM settings WHERE user = #ulogin"
Using cmd = new MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", Me.loginuser.Text)
cmd.ExecuteNonQuery()
End Using
End Using
First and foremost, do not use string concatenation to create command texts to pass to the database engine. In that way you risk Sql Injections, also, if the user name contains a single quote (i.e. O'Hara) your code will fail with a syntax error (Same problems arise for date formatting, parsing numeric decimals and other globalization issues). Instead a parametrized query like the one in code above will avoid all of these problems.
In a parametrized query, the text of the query doesn't contains the actual value for the search condition or the update or insert data. Instead it contains placeholders ( in our case it is called #ulogin). The correct value to insert at the placeholders position is specified using one or more MySqlParameter added to the Parameters collection of the MySqlCommand. In this case I have used the AddWithValue method that derives the correct datatype directly from the datatype of the value. Because Me.loginuser.Text is a string value then the parameter will be treated as a string value replacing incorrect single quotes and removing extraneus characters usually used to Mount Sql Injections Attacks. The engine will do the rest inserting the correct value at the placeholder at execution time
EDIT: Seeing your comment about the MySql connector used, I will try to update my answer to show a semi-equivalent version for NET 1.
Try
Dim con As MySqlConnection = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText as String = "DELETE * FROM settings WHERE user = #ulogin"
Dim cmd As MySqlCommand = new MySqlCommand(sqlText, con)
Dim par As MySqlParameter = New MySqlParameter("#ulogin", MySqlDbType.VarChar)
par.Value = Me.loginuser.Text
cmd.Parameters.Add(par)
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
I am not sure if the connector 1.0.10 supports the parameter name with the # prefix or just the : prefix
i dont think you can use double quotes in mysql, i think its single quotes only. try
Query = "DELETE * FROM settings WHERE user = '" & Me.loginuser.Text & "'"

how to add rows to mysql database table and display it in a listbox in vb.net?

I have the following controls:
textbox1 - this is where i type a message.
listbox1 - this is where i display the messages.
button1 - this is what posts my messages to the server.
StatusStrip1.Title1 - this is where the current user's title will go. (i.e: Administrator, manager... etc.)
I have a table on a MYSQL database called "messages" and a column called "message". When i type something into textbox1 and click button1 i want to add a row to "messages" under the column "message" with the title and message as its value.(separated by a hyphen, dash, or other small delimiter)Then reload listbox1's contents to show the new message.
so i want the final message to be something like:
Administrator - Hello World!
I currently have the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO messages(message) VALUES(?name - ?message)"";", con)
sqlpost.Parameters.AddWithValue("?name", Title2.Text)
sqlpost.Parameters.AddWithValue("?message", TextBox1.Text)
Try
con.Close()
con.Open()
' Sending message.
If TextBox1.Text = "" Then
MessageBox.Show("You forgot to type a message!")
Else
sqlpost.ExecuteNonQuery()
' Reloading messages.
ListBox1.Items.Clear()
reader = sqlmessages.ExecuteReader()
While (reader.Read)
ListBox1.Items.Add(reader.Item("message"))
ListBox1.Items.Add("")
End While
reader.Close()
con.Close()
TextBox1.Text = ""
Label4.Text = "Message Sent!"
Timer2.Start()
End If
Catch myerror As MySqlException
MessageBox.Show("Error sending message to server: " & myerror.Message)
End Try
End Sub
I had it working before, but when i made changes to it, it came up with various sql statement syntax errors... (stuff like invalid truncated value of "Administrator", or invalid DOUBLE value "hello") and now it won't even display any messages currently in the "messages" table...)
If anyone could tell me what i'm doing wrong, or a more efficient way of doing this then i would greatly appreciate it! Thanks!
One thing I see that looks incorrect is that you are using "?" for you parameter names in the query. The default character to use for parameter names is to start them with "#". Although I think there's a connection string option to use "?" as that is what was used in the older versions of the MySQL connector, but the current default is "#". Also, there seems to be some problems with your command in general. You have:
Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO messages(message) VALUES(?name - ?message)"";", con)
it should probably be something more like
Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO messages(message) VALUES(#message);", con)
I fixed up the query a bit, and replaced the ? with #. You you can do the concatenation of name and message (as you cleared up in the comment) in VB, with some code such as this:
sqlpost.Parameters.AddWithValue("#message", Title2.Text & " - " & Title2.Text)
I also see that you are calling
sqlmessages.ExecuteReader()
but I don't see where this is being initialized.
You should have to use single parameter.
Dim con as New MySqlConnection
con.ConnectionString="set_connection_string_here"
Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO `messages` (`message`) VALUES (#name)",con)
sqlpost.Parameters.AddWithValue("#name", Title2.Text & " - " & TextBox1.Text)
If TextBox1.Text = "" Then
MessageBox.Show("You forgot to type a message!")
Else
con.Open()
sqlpost.ExecuteNonQuery()
con.Close()
ListBox1.Items.Clear()
sqlmessages.CommandText="select * from `messages`"
sqlmessages.Connection=con
reader = sqlmessages.ExecuteReader()
While (reader.Read)
ListBox1.Items.Add(reader.Item("message"))
End While
reader.Close()
con.Close()
End If