Put data from MySQL to labels in a table in vb.net - mysql

I want to put sum of each month in a label in the table from MySQL database but i dont know to make it in the label cz i have lbl1, lbl2, ... lbl12.
My code:
connection.Open()
query = " SELECT SUM(Amount_income_table), MONTHNAME(Date_income_table)
FROM bacci.income_table
where year(Date_income_table)='" & LblYear.Text & "'
GROUP BY MONTHNAME(Date_income_table);"
Comand = New MySqlCommand(query, connection)
READER = Comand.ExecuteReader
While READER.Read
ChartIncomeYear.Series("Incomes").Points.AddXY(READER.GetString("MONTHNAME(Date_income_table)"), READER.GetString("SUM(Amount_income_table)"))
End While
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
this code will fill the chart but i also want to fill the labels with the same query.

you shouldn't have your label as lbl1, lbl2 and lbl3 etc. You should create them at run time. Try this code i a blank project. Adapt your code from this example. I like using list of objects but you can use an array too
Dim LabelList As List(Of Label)
Sub LoadSumLabel()
LabelList = New List(Of Label)
For x = 1 To 12
Dim NewLabel As New Label
With NewLabel
.Name = DateAndTime.MonthName(x)
.Text = "0"
.AutoSize = True
.Left = 10
.Top = 10 + (LabelList.Count * NewLabel.Height)
End With
LabelList.Add(NewLabel)
Me.Controls.Add(LabelList.Item(LabelList.Count - 1))
AddHandler LabelList.Item(LabelList.Count - 1).Click, AddressOf Label_Click
'you can create a panel and add you control to it the same way. So if you resize the form you can have the scroll bars if it doesnt fit
'somepanel.controls(LabelList.Item(LabelList.Count - 1))
Next
End Sub
Private Sub Label_Click(sender As Object, e As EventArgs)
Dim thisLabel As Label = DirectCast(sender, Label)
MsgBox(thisLabel.Name, vbOKOnly, "Result")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
LoadSumLabel()
End Sub
Sub RunQuery()
connection.Open()
query = " SELECT SUM(Amount_income_table), MONTHNAME(Date_income_table)
FROM bacci.income_table
where year(Date_income_table)='" & LblYear.Text & "'
GROUP BY MONTHNAME(Date_income_table);"
Comand = New MySqlCommand(query, connection)
READER = Comand.ExecuteReader
While READER.Read
ChartIncomeYear.Series("Incomes").Points.AddXY(READER.GetString("MONTHNAME(Date_income_table)"), READER.GetString("SUM(Amount_income_table)"))
LabelList.Find(Function(lb As Label) lb.Name = READER.GetString("MONTHNAME(Date_income_table)")).Text = READER.GetString("SUM(Amount_income_table)")
End While
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
End Sub

Name your labels like this lblJanuary, lblFebruary, lblMarch .... lblDecember. And then you can easily solve your problem using this code :
query = " SELECT SUM(Amount_income_table) as Total, MONTHNAME(Date_income_table)
FROM bacci.income_table
where year(Date_income_table)='" & LblYear.Text & "'
GROUP BY MONTHNAME(Date_income_table);"
Comand = New MySqlCommand(query, connection)
READER = Comand.ExecuteReader
While READER.Read
ChartIncomeYear.Series("Incomes").Points.AddXY(READER.GetString("MONTHNAME(Date_income_table)"), READER.GetString("SUM(Amount_income_table)"))
Me.Controls("lbl" & READER.GetString("MONTHNAME(Date_income_table)")).Text = READER.GetString("Total")
End While
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try

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

VB NET + Substring + Mysql + Check Rows

I have a simple form with a button and 2 textbox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection(ConfigurationManager.ConnectionStrings("db.My.MySettings.dbConnectionString").ToString)
Try
'MysqlConn.Dispose()
'MysqlConn.Close()
MysqlConn.Open()
Dim str As String
str = "SELECT substring_index(substring(path,1,locate(substring_index(path,'\\',-1),path)-2),'\\',-1)as PATH FROM foto where id_product = '" & TextBox2.Text & "'"
Dim dbCommand As New MySqlCommand(str, MysqlConn)
Dim dbReader = dbCommand.ExecuteReader
While dbReader.Read()
If IsDBNull(dbReader(0)) OrElse String.IsNullOrEmpty(dbReader.GetString(0)) Then
TextBox1.Text = "0"
Else
TextBox1.Text = dbReader.Item("PATH")
End If
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
when i put in textbox2 "1" i have my desired value.
But when i put "2", this id_product dont exist, i dont have "0".
It's blank and Textbox1 has my previous value.
What i do wrong ??
If the query doesn't return any record, your code doesn't enter the while loop (dbReader.Read return false) and thus you don't set the textbox to "0" but you should also start to use parameterized queries. It is very important to avoid possible parsing errors and mainly to avoid Sql Injection attacks
So, you could test if your query has produced any record verifying the property HasRows of the DataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using MysqlConn = New MySqlConnection(ConfigurationManager.ConnectionStrings("db.My.MySettings.dbConnectionString").ToString)
Try
MysqlConn.Open()
Dim str As String
str = "SELECT substring_index
(substring(path,1,
locate(substring_index(path,'\\',-1),path)-2),
'\\',-1) as PATH
FROM foto where id_product = #pid"
Dim dbCommand As New MySqlCommand(str, MysqlConn)
dbCommand.Parameters.Add("#pid", MySqlDbType.VarChar).Value = textBox2.Text
Using dbReader = dbCommand.ExecuteReader
if dbReader.HasRows Then
While dbReader.Read()
If IsDBNull(dbReader(0)) OrElse String.IsNullOrEmpty(dbReader.GetString(0)) Then
TextBox1.Text = "0"
Else
TextBox1.Text = dbReader.Item("PATH")
End If
End While
else
TextBox1.Text = "0"
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub

how to display selected value in mysql database in label through vb.net

i have a code but it's not working. i was trying to put a value in label2 but it's not working. please help me.
Private Sub student_no_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles student_no.Click
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = sample;"
Dim READER As MySqlDataReader
Try
MySqlConnection.Open()
Dim query As String
query = " select id from sample.student where last_name = '" & txtlastname.Text & "' "
Dim Command As New MySqlCommand(query, MySqlConnection)
READER = Command.ExecuteReader
Label2.Text = query.ToString
MessageBox.Show("Student Number Generated")
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
You are using .ToString on query, which is a string. What you should be doing is operations on the READER object.
Since SELECT will always return a list of results, you have to treat the results as such, like...
While READER.Read()
MessageBox.Show((READER.GetInt32(0)))
End While
.Read() returns the next element in the returned rowset
If READER.Read() Then
Label2.Text = READER.GetString(0)
End If

If user input a value that doesn't exist on database it will set text label with MySQL using VB.Net

What's the exact query for that? The best that I was able to come up with is setting the TextLabel message if what the user input is blank, but not if what the user inputted is wrong. I don't know the right query for it. I tried NULL but I don't know the exact query for it so I tried = Nothing and it did Nothing. Here's my code:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim connString As String = "server=localhost;userid=root;password=;database=cph;Convert Zero Datetime=True"
Dim sqlQuery As String = "SELECT emp_firstnm, emp_midnm, emp_lastnm FROM employee_table WHERE emp_no = #empno"
If txtEmpno.Text = Nothing Then
Label4.Text = "No such employee exists"
Else
Using sqlConn As New MySqlConnection(connString)
Using sqlComm As New MySqlCommand()
With sqlComm
.Connection = sqlConn
.CommandText = sqlQuery
.CommandType = CommandType.Text
.Parameters.AddWithValue("#empno", txtEmpno.Text)
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
Label4.Text = sqlReader("emp_firstnm").ToString() & " " & sqlReader("emp_midnm").ToString() & " " & sqlReader("emp_lastnm").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
sConnection.Dispose()
End Try
End Using
End Using
End If
End Sub
Use String.IsNullOrEmpty.
If (String.IsNullOrEmpty(txtEmpno.Text)) Then
Or
If (txtEmpno.Text = String.Empty) Then
...which is the equivalent of
If (txtEmpno.Text = "") Then
A String is a reference type (class) and can be set to Nothing. But, by design, a label will always return an empty string "", not a null.
txtEmpno.Text = Nothing
MessageBox.Show(String.Format("{0}, {1}", (txtEmpno.Text Is Nothing), (txtEmpno.Text = "")))
Will output:
False, True

how to display mysql result to label or text?

Need to display the result of a mysql string to a label or textbox.
Only got a code to embed the results to a listview:
Sub fillListview()
Try
ListView1.Items.Clear()
strSQL = "SELECT * FROM customer"
objCmd = New MySql.Data.MySqlClient.MySqlCommand(strSQL, objConn)
objDR = objCmd.ExecuteReader
While (objDR.Read())
With ListView1.Items.Add(objDR("Cust_Id"))
.subitems.add(objDR("Cust_Name"))
.subitems.add(objDR("Cust_Age"))
.subitems.add(objDR("Items"))
.subitems.add(objDR("Price_Accumulated"))
.subitems.add(objDR("Date"))
.subitems.add(objDR("Time"))
End With
End While
objCmd.Dispose()
objDR.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Also i've already put strsql, objCmd etc. as a variable in a module so no need for it to be a DIM
(BTW I don't know why only the While is recognized as a code :|)
try this format:
Sub fillListview()
Try
ListView1.Items.Clear()
strSQL = "SELECT * FROM customer"
objCmd = New MySql.Data.MySqlClient.MySqlCommand(strSQL, objConn)
objDR = objCmd.ExecuteReader
While (objDR.Read())
textBox.Text=objDR("Cust_Id").toString()
End While
objCmd.Dispose()
objDR.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
place this inside the while statement.