Database values in textbox if select Combobox vb.net mysql - 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.

Related

VB.NET MySQL query returns no value

I am trying to display value in combobox using MySQL in vb.net. Right now the problem that I am facing is that combobox is not displaying values from MySQL. I have the below code:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
However, using the above code Combobox1.Text returns nothing but if I use below code which has a different query it works:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("Name")
ComboBox1.Items.Add(sName)
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Could someone please check and let me know what could be the issue? Thanks!
so the highlights as i mentioned them in the comments
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' You need only to open aconnection once
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "db connection successful"
'First load both Combobox
Dim query As String
query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sname = READER.GetString("name")
ComboBox1.Items.Add(sname)
ComboBox2.Items.Add(sname)
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Closing
Try
MySqlConn.Close()
MySqlConn.Dispose()
Catch ex As Exception
End Try
End Sub
ANd now the Comboboxes
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'Only when there is a item selected , ask for data
If ComboBox1.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label11.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
This is exactly as i described on Form_load you fill both comboboxes
When you now change one of the comboxes one of the label change too.
Sometimes you have to update the Element to see a change
in that case you write at the end of the loop
Label10.Update()
Starting at the top...
Keep your database objects local to the method where they are used. (Not Form level variables) You can make the connection string a class level string variable. This is the only way you can ensure that they are closed and disposed.
Using...End Using blocks will close and dispose your database objects even if there is an error. The constructor of the connection takes the connection string. Connections are precious objects. Don't open the connection until directly before the .Execute method and close it as soon as possible.
It doesn't make much sense that the user could select an item from ComboBox1 before the Form.Load.
In general, we don't want to download anymore data than necessary and we want to hit the database as little as possible. In the Form.Load we bind the combobox to a data table that contains the name and price fields, setting the display and value members. Now, whenever the user picks a name in the combo we can retrieve the price without connecting to the database again.
I noticed that you were using Val in another event. This is an old VB6 method that can give you unexpected results. .Net and vb.net have all sorts of ways to get numbers out of strings that are faster and more reliable. CInt, .TryParse, .Parse, CType, Convert.To etc.
Public Class Form1
Private ConString As String = "server=localhost;userid=root;password=root;database=s974_db"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Fill combobox
Dim dt As New DataTable
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("select Name, Price from processors;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using 'Closes and disposes both connection and command
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Price"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Label10.Text = ComboBox1.SelectedValue.ToString
ClearLabels()
End Sub
Private Sub ClearLabels()
Label11.Text = ""
Label12.Text = ""
Label13.Text = ""
Label14.Text = ""
Label15.Text = ""
Label16.Text = ""
Label17.Text = ""
Label18.Text = ""
Label19.Text = ""
Label20.Text = ""
End Sub
End Class

Populate Label in VB from MySQL select query

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

My code isn't updating my database even though no error is popping up

It doesn't show me any error and tells me its saved. If I replace the userlable.text with a real value in the database, it works. But with the userlable.text its not working. I have done something similar on another vb.form and it worked so why wouldn't this? It doesn't update in T1Marks on the row where the username is but it says it worked. Any help please?
Private Sub Finish1Button_Click(sender As Object, e As EventArgs) Handles Finish1Button.Click
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=Red-grape01;database=math"
Try
con.Open()
Dim Order As String
Order = "update math.marks set T1Marks='" & MarkLable.Text & "' WHERE Username='" & userlabel.Text & "'"
cmd = New MySqlCommand(Order, con)
datareader = cmd.ExecuteReader
MessageBox.Show("Saved")
con.Close()
Catch ex As MySqlException
MessageBox.Show("Error")
Finally
con.Dispose()
End Try
ExamTopicSelectionPage.Show()
Me.Close()
End Sub

Trying to enter records into a mysql database using vb.net but its not working and I cant figure out why

Mysql is connected to my vb so thats not the problem Im not really sure whats wrong.
This is a register account form, im using xampp for mysql.
Public Class Reigsteraccount
Public Class Form1
Dim conn As MySqlConnection
Dim COMMAND As MySqlCommand
Dim WithEvents Button1 As New Button
Dim WithEvents Textbox1 As New TextBox
Dim WithEvents Textbox2 As New TextBox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;userid=root;password=root;database=compproject"
Dim READER As MySqlDataReader
Try
conn.Open()
Dim Query As String
Query = "insert into compproject.users (Usernames,Passwordhash) values ('" & Textbox1.Text & "','" & Textbox2.Text & "')"
COMMAND = New MySqlCommand(Query, conn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Record added")
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
First of all, that's some very bad code - I know this isn't CodeReview, but still, it needs to be pointed out! Have a look at codereview.stackexchange.com if you want to brush up on best practices (I appreciate you might be a first time coder...).
To answer the question, you are using COMMAND.ExecuteReader - this should be replaced with COMMAND.ExecuteNonQuery. You're not reading from the database, you're writing data into it (INSERT command in the SQL).
If it still doesn't work after changing that, please update your question to include more detail, such as the exception generated, etc.

Update mysql table in vb.net using datagridview

Hi guys I need help in updating the data on my datagridview. The Scenario is when I click the Search button it will query the appropriate data and display that I want to the datagridview. Then I want to update if their any changes or deleted data from datagridview then also update to my mysql table for new data or record whenever I click the Update Button. The problem is that when I click my search button the messagebox appears "The table contains no changes to save." this means there is no changes but i already change values in datagridview. Anyone could help me?
Here is for my search button code:
Public Class Form1
Dim con As New MySqlConnection
Dim result As Integer
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim sql As String
Dim dt As New DataTable
Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
Dim conn As New MySqlConnection
conn.ConnectionString = ("server=127.0.0.1;user id=root;password=12345;database=dbsis3bkenth;")
Try
conn.Open()
sql = "SELECT LName,FName,MI FROM tblsisterbrother where IDNoBrodSis = '" & cbIDNo.Text & "'"
cmd = New MySqlCommand(sql, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = True Then
MessageBox.Show("Record Found.!")
Else
MessageBox.Show("Record Unfound.!")
End If
dr.Close()
Catch ex As MySqlException
MessageBox.Show("Error in searching to database:error is:" & ex.Message)
Exit Sub
End Try
dr.Close()
RemoveHandler DataGridView1.CellValidating, AddressOf DataGridView1_CellValidating
da.SelectCommand = cmd
da.Fill(ds, "tblsisterbrother")
DataGridView1.DataSource = ds.Tables(0)
conn.Dispose()
conn.Close()
End Sub
Here is the code for my update button:
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = New MySqlCommandBuilder(da)
Dim rowsAffected As Integer = da.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
End Class
Please help me guys to solve my problem :)
According to the MSDN page about GetChanges:
Gets a copy of the DataTable that contains all changes made to it since it was loaded or AcceptChanges was last called.
Since you're declaring the DataTable and loading it only one time, it's working as expected.
To make it work like you want you'll have to use the CellEditEnd event, and call the GetChanges() method from DataGrid.DataSource, something like this:
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Dim Changes As DataTable
Changes = TryCast(DataGridView1.DataSource, DataTable).GetChanges()
End Sub