Populate Label in VB from MySQL select query - mysql

I have found a few articles that are similar to my question, and I have tried the suggestions in those articles and none of them have worked for me. What I need seems to be fairly simple and straight forward. (I am able to complete this same action with SQL Server, just not with MySQL. This 'description' information must come a MySQL db)
I have a Listbox and as the user clicks on listbox items, I would like a 'description' label to update with a value pulled from a MySQL database.
I created a public sub in the Module, and I'm calling the sub from the Listbox1_SelectedIndexChanged event (also tried Listbox1_mouseclick event).
However, everything I have tried does not update the label. Any suggestions would be greatly appreciated.
here is the code being used to pull and attempt to populate the label:
Dim conn As New MySqlConnection(My.Resources.MySqlstr)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand("select Description from resourceaccess where tid = '" & ReportPicker.ListBox1.ValueMember & "' ", conn)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
ReportPicker.Label3.Text = reader.GetString("Description")
End While
reader.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try

I don't know if something else is wrong too but this definitely is:
Dim cmd As MySqlCommand = New MySqlCommand("select Description from resourceaccess where tid = '" & ReportPicker.ListBox1.ValueMember & "' ", conn)
Apart from the fact that you should be using a parameter there, the use of ValueMember can't possibly be right. That's the name of a column, not a value from that column. You should be using SelectedValue, which is the value from that column for the item that's selected.

here is what worked:
Dim cs As String = My.Resources.MySqlstr
Dim stm As String = "select Description from resourceaccess where resource = '" & ReportPicker.ListBox1.Text & "' "
Dim conn As MySqlConnection = New MySqlConnection(cs)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(stm, conn)
ReportPicker.Label3.Text = Convert.ToString(cmd.ExecuteScalar())
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try

Related

How do I write to a Mysql database in VB.net with a query

I am trying to make a little program that writes and reads from a Mysql database. The reading part is going well, but I am a bit stuck in the write part.
This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Absenden.Click
Dim conn As New MySqlConnection
Dim command As MySqlCommand
Dim myConnectionString As String
myConnectionString = "server=Nothing;uid=to;pwd=see;database=here;"
conn.ConnectionString = myConnectionString
Try
conn.Open()
Dim Querywrite As String
Querywrite = "select * FROM here.message INSERT INTO message admin='" & TB_Name.Text & "' and message='" & TB_Nachricht.Text & "' and Server='" & TB_Server.Text & "' and status='" & TB_Status.Text & "' "
command = New MySqlCommand(Querywrite, connection)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
conn.Close()
End Sub
The Querywrite part is the problem I think. The input comes from Textboxes in a Windows Form.
Thanks for your help!
Perhaps, if someone shows you once then you will get the idea. The main thing is to always use parameters; not only will you avoid minor sytax and type errors but you will avoid major disasters of malicious input. I guessed at the datatypes of your fields. Please check your database for the types and adjust your code accordingly.
Private Sub InsertData()
Dim strQuery As String = "Insert Into message (admin, message, Server, status) Values (#admin, #message, #Server, #status);"
Using cn As New MySqlConnection("your connection string")
Using cmd As New MySqlCommand With {
.Connection = cn,
.CommandType = CommandType.Text,
.CommandText = strQuery}
cmd.Parameters.Add("#admin", MySqlDbType.VarString).Value = TB_Name.Text
cmd.Parameters.Add("#message", MySqlDbType.VarString).Value = TB_Nachricht.Text
cmd.Parameters.Add("#Server", MySqlDbType.VarString).Value = TB_Server.Text
cmd.Parameters.Add("#status", MySqlDbType.VarString).Value = TB_Status.Text
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Using
End Using
End Sub

Database values in textbox if select Combobox vb.net mysql

i cant figure out my problem there is no error but value in combobox not showing from mysqldatabase
here is my code
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New MySqlConnection
conn.ConnectionString = "server=localhost;user vbid=root;password=admin;database=dnidb"
Dim reader As MySqlDataReader
Try
conn.Open()
Dim query As String
query = "select * from dnidb.hargapro where NamaP = '" & ComboBox1.Text & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
While reader.Read
TextBox8.Text = reader.GetInt32("HargaP")
End While
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
this code was no error, but didnt show anything in the combobox, i try to make this cone on combobox_selectedindexchanges and same thing nothing showing up in the combobox
i just follow the code from here
https://www.youtube.com/watch?v=HfnoGEmRGvc
I don't see any code that tries to retrieve the product names to combobox, and it seems like the above code should be on SelectedIndexChanged event of the combobox.

Show Date with DateTimePicker from MySQL

I'm at the moment having a problem with my program I want to retrieve the Date that is in MySQL DB to show the Date/Week/Year I choose in the DateTimePicker in my ListView but I encountered a problem and can't see the solution nor have I found something that looks like it:
Try
conn.Open()
Dim Reader As MySqlDataReader
Dim Query As String
Query = "Select * from farm.sales where datesale= ('" & DateTimePicker1.Text & "') "
command = New MySqlCommand(Query, conn)
Reader = command.ExecuteReader
While Reader.Read
Dim Datesale = Reader.GetString("datesale")
Dim Clients= Reader.GetString("clients")
Dim Bank= Reader.GetString("bank")
Dim Revenue= Reader.GetString("revenue")
Dim Total = Reader.GetString("total")
Dim LV As New ListViewItem
LV.Text = Reader("Datesale").ToString
LV.SubItems.Add(Reader("Clients").ToString)
LV.SubItems.Add(Reader("Bank").ToString)
LV.SubItems.Add(Reader("Revenue").ToString)
LV.SubItems.Add(Reader("Total").ToString)
ListView1.Items.Add(LV)
End While
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
The problem I'm getting is in this line LV.Text = Reader("Datesale ").ToString, which I assume its because of the format I'm retrieving but I can't find a solution can someone pls help me get to a solution
Thanks
Edit:
My bad didn't post the error the problem the program crashes and I get the error An unhandled exception of type System.IndexOutOfRangeException occurred in MySql.Data.dll
Additional information: Could not find specified column in results: Datesales
this is how I use listview. I hope this helps.
conn.Close()
conn.Open()
cmd.CommandText = "SELECT * FROM tblUser"
cmd.Connection = conn
dr = cmd.ExecuteReader
While dr.Read
Dim itm = frmAdminMain.lvUser.Items.Add(dr("UserID"))
itm.SubItems.Add(dr("Username"))
itm.SubItems.Add(dr("Password"))
itm.SubItems.Add(dr("FName"))
itm.SubItems.Add(dr("LName"))
itm.SubItems.Add(dr("Title"))
itm.SubItems.Add(dr("Department"))
End While
dr.Close()
conn.Close()
i used lvUser.Items.Add(dr("UserID"))
in your case, you used LV.text..
just change it to LV.Items.Add(Reader.GetString("datesale")
goodluck! :)
Finally resolved it don't know what the error actually was I simply changed the name of the variable and the name on the listview and it solved it
Thanks so much for the replys and

Updating MYSQL records via VB.NET

What I am trying to do is do the basic insert, refresh and update mysql querys in my vb.net application. The refresh, and the insert work perfect the only one I can't get is the update can anyone tell me what I am doing wrong? Here is a picture of the program layout:
http://i.imgur.com/mHxKGrb.png
and here is my source code:
Private Sub KnightButton3_Click(sender As Object, e As EventArgs) Handles KnightButton3.Click
cn = New MySqlConnection
cn.ConnectionString = "my info"
Try
cn.Open()
Dim query As String
Dim command As MySqlCommand
query = "UPDATE Refers.exploitsociety SET Refferals='" + refupdate.Text + "' WHERE Refferals='" + DataGridView1.CurrentCell.Selected + "';"
command = New MySqlCommand(query, cn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
cn.Dispose()
End Try
cn.Close()
End Sub
I think your problem is in the usage of the property Selected of the CurrentCell. This is a boolean value and it is not the content of that cell.
I would use this kind of code with a parameterized query and a using statement around disposable objects
Try
query = "UPDATE Refers.exploitsociety " & _
"SET Refferals=#refs " & _
"WHERE Refferals=#oldrefs"
Using cn = New MySqlConnection(".... connection string ....")
Using command = New MySqlCommand(query, cn)
cn.Open()
command.Parameters.Add("#refs", MySqlDbType.Int32).Value = _
Convert.ToInt32(refupdate.Text)
command.Parameters.Add("#oldrefs", MySqlDbType.Int32).Value = _
Convert.ToInt32(DataGridView1.CurrentCell.Value.ToString())
command.ExecuteNonQuery()
End Using
End Using
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
Notice that with a using statement you don't need to close/dispose the connection because this is automatically done when the code leaves the using block (also in case of exceptions)

How to populate a ComboBox depending on the selected item from another ComboBox in VB

I have tables inside my MySql database:
material
unitofmeasure
I also have 2 comboboxes:
cmbHeader - this combobox populates the tables inside the database.
cmbContent - this combobox SHOULD populate the columns inside the table selected from cmbHeader
I was able to populate the cmbHeader with the tables inside my database using this code:
Dim conn As New MySqlConnection
Dim command As New MySqlCommand
Dim dt As New DataTable
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
dt = conn.GetSchema("TABLES")
cmbHeader.DataSource = dt
cmbHeader.DisplayMember = "table_name"
cmbHeader.ValueMember = "table_name"
command.Dispose()
conn.Close()
Catch ex As Exception
End Try
Now for the cmbContent, I get an error in my code. I use this code:
Private Sub cmbHeader_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbHeader.SelectedIndexChanged, cmbList.SelectedIndexChanged
Dim conn As New MySqlConnection
Dim command As New MySqlCommand
Dim dt As New DataTable
Dim reader As MySqlDataReader
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
conn.Open()
Dim query As String
query = "SELECT * FROM '" & cmbHeader.SelectedItem & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
cmbList.Items.Clear()
While reader.Read
Dim header = reader.GetString("Header")
Dim content = reader.GetString("Content")
Dim convert = reader.GetString("Convert")
cmbList.Items.Add(content)
End While
command.Dispose()
reader.Close()
conn.Close()
End Sub
This is the image of the error that I get using the code above.
I tried changing my query to "SELECT * FROM '" & cmbHeader.SelectedItem.ToString & "'" but I get a different error. How can I populate my 2nd ComboBox depending on what I choose on my 1st ComboBox? Please help I'm stuck. Thanks. :)
Replace following line in your code,
query = "SELECT * FROM '" & cmbHeader.SelectedItem & "'"
with this line,
query = "SELECT * FROM " & cmbHeader.SelectedItem.Value & ";"
Hope this will work.
Thank you.
make your query as like this:
query = "SELECT * FROM " & cmbHeader.Text '<-- updation
OR
query = "SELECT * FROM " & cmbHeader.SelectedValue '<-- updation
but it is not a good practice as it lead to sql injection so i suggest you to do it using parametrized(in this case injuction can be avoided as it allows only selected values from the combo box. but in general it is not a good practice that's why am suggesting like this) query as like the following
query = "SELECT * FROM ?"
Dim cmd As New OdbcCommand
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = con
.Parameters.Add(New OdbcParameter(#table,cmbHeader.SelectedItem ))
End With
FOR OTHER PEOPLE WHO HAVE THE SAME PROBLEM
I was able to figure out what's wrong with my code. The value of the combobox I'm getting returns "Data.Row.DataRowView" that's why my query fails. I changed this:
cmbHeader.DataSource = dt
cmbHeader.DisplayMember = "table_name"
cmbHeader.ValueMember = "table_name"
into this:
cmbHeader.ValueMember = "table_name"
cmbHeader.DisplayMember = "table_name"
cmbHeader.DataSource = dt
Then on my SelectedIndexChanged event, I used this:
Dim value As String = ""
value = Convert.ToString(cmbHeader.Text)
conn.Open()
Dim query As String
query = "SELECT * FROM " & value
command = New MySqlCommand(query, conn)
'With command
' .Parameters.AddWithValue("header", value)
'End With
reader = command.ExecuteReader
cmbList.Items.Clear()
While reader.Read
Dim content = reader.GetString("Content")
cmbList.Items.Add(content)
End While
command.Dispose()
reader.Close()
conn.Close()
Hope this helps. Thanks for the help everyone. :)