vb.net setting data source to combobox - mysql

i want to set a data source to my combobox when i run there s no error but it keeps showing zeros in the combobox
Dim cnx As New MySqlConnection("datasource=localhost;database=bdgeststock;userid=root;password=")
Dim cmd As MySqlCommand = cnx.CreateCommand
Dim da As MySqlDataAdapter
Dim ds As New DataSet
If ConnectionState.Open Then
cnx.Close()
End If
cnx.Open()
cmd.CommandText = "SELECT idf,(prenom + ' ' + nom) AS NAME FROM fournisseur "
da = New MySqlDataAdapter(cmd)
cnx.Close()
da.Fill(ds)
da.Dispose()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "idf"
ComboBox1.DisplayMember = "NAME"

For ComboBox data source you probably don't need heavy Data Set or DataTable - collection of plain object will do the job.
Another approach would be to move representation logic to the vb.net code and leave sql server to do persistence logic only.
Public Class Fournisseur
Public ReadOnly Property Id As Integer
Public ReadOnly Property Name As String
Public Sub New(id As Integer, prenom As String, nom As String)
Id = id
Name = $"{pronom} {nom}".Trim()
End Sub
End Class
You can create dedicated function to load data
Private Function LoadItems() As List(Of Fournisseur)
Dim query = "SELECT idf, prenom, nom FROM fournisseur"
Using connection As New MySqlConnection(connectionString)
Using command As New MySqlCommand(query, connection)
connection.Open()
Dim items = new List(Of Fournisseur)()
Using reader AS MySqlDataReader = command.ExecuteReader()
While reader.Read()
Dim item As New Fournisseur(
reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2)
)
items.Add(item)
End While
End Using
Return items
End Using
End Using
End Function
Then usage will look pretty simple
ComboBox1.ValueMember = "Id"
ComboBox1.DisplayMember = "Name"
ComboBox1.DataSource = LoadItems()

I think the problem is in your sql, and mysql is performing some sort of numeric addition on prenom plus nom and producing 0
Try
CONCAT(prenom, ' ', nom) as name
In your sql instead. I prefer using concat in most RDBMS for concatenating strings because is is more consistent with its behaviour on NULLs - in sqlserver, using the concat operator of plus on something like 'a' + null results in NULL but in oracle 'a' || null is a - in both the CONCAT behaviour is consistent
Here's a full code with all my recommendations:
Dim cnstr = "datasource=localhost;database=bdgeststock;userid=root;password="
Dim cmd = "SELECT idf, CONCAT(prenom, ' ', nom) AS nom FROM fournisseur "
Using da As New MySqlDataAdapter(cmd, cnstr)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.ValueMember = "idf"
ComboBox1.DisplayMember = "nom"
End Using
Tips:
you don't need to mess around with the connection: dataadapter will create/open/close it for you
use a datatable not a dataset
use Using
use the constructor of MySqlDataAdapter that takes a connectionstring and a command text- shorter and nearer in this case. I only use the constructor that takes a DbConnection if I'm manually enrolling multiple commands in a transaction etc

Related

Remove duplicated rows on gridview

Hi There I have the following grid view developed with vb.net and html
This is the code to fill the gridview
Private Sub BindGrid()
Dim modelo As String = txtModelo.Text
Dim linha As String = txtLinha.Text
Dim data As String = txtData.Text
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT * FROM tempo where timermodelo = #timermodelo and timerlinha = #timerlinha and timerdata = #timerdata")
Using sda As New MySqlDataAdapter()
cmd.Parameters.AddWithValue("#timermodelo", modelo)
cmd.Parameters.AddWithValue("#timerlinha", linha)
cmd.Parameters.AddWithValue("#timerdata", data)
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End Sub
My question is, is it possible to remove the duplicated rows on the column Operador, Posto, Linha and Modelo?
And also how can I form the date to show 'dd-mm-yyyy'?
Actually, I want to merge these values, if they are the same, show just one time
Sorry if it is difficult to understand, if more information is needed let me know
Thanks in advance
Remove duplicates : Why don't you use SqlStatement that return rows without duplication, depending on your Database type 'you did not mention', if this is achievable in your SqlStatement then this problem is solved.
Format Date in GridView1 cell : Use GridView1_CellFormatting event [ Where your Date ColumnIndex = 4] as follows
Private Sub GridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
If Not IsNothing(e.Value) Then
If e.ColumnIndex().ToString = 4 And IsDate(e.Value) Then
e.Value = Format(e.Value, "dd-mm-yyyy")
End If
End If
End Sub
I want to merge these values, if they are the same
What values are we talking about here ?

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

Hide part of String.Format within a ComboBox.Item

Is it possible to hide part of String.Format?
This my code:
'Select Product'
Try
MysqlConn.Close()
MysqlConn.Open()
Dim Query As String
Query = "select id, name,id_maker, id_types from product ORDER BY name ASC"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("name")
Dim sMaker = READER.GetString("id_maker")
Dim sTypes = READER.GetString("id_types")
Dim sId = READER.GetString("id")
'ComboBox1.Items.Add(sName)'
ComboBox1.Items.Add(String.Format("{0}|{1}|{2}|{3}", sName, sMaker, sTypes, sId))
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
'Select Product'
I want to hide {3} which is sId in the ComboBox, because later I need to use a query where the ComboBox1.Text is used and the id is necessary.
Maybe you could change the way you are assigning the data to the ComboBox.
First thing to do is change the query and use CONCAT:
SELECT id, CONCAT(name,'|',id_maker,'|',id_types) AS value FROM product ORDER BY name ASC
I would also implement Using:
Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.
You also don't need the READER. Instead load the data into a DataTable and assign that to the .DataSource property on the ComboBox.
Your code would look something like this:
Using con As New MySqlConnection(connectionString)
cmd As New MySqlCommand("SELECT id, CONCAT(name,'|',id_maker,'|',id_types) AS value FROM product ORDER BY name ASC", con)
con.Open()
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "value"
ComboBox1.ValueMember = "id"
End Using
You can now get the id with this bit of code:
ComboBox1.SelectedValue.ToString()
And you can get the text with this bit of code:
ComboBox1.Text
Ok i use now that and works
Dim connetionString As String = Nothing
Dim connection As MySqlConnection
Dim command As MySqlCommand
Dim adapter As New MySqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
'connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword"
'sql = "select id,name from product"
sql = "SELECT id, CONCAT(name,' | ',id_maker,' | ',id_types) AS value FROM product ORDER BY name ASC"
'connection = New MySqlConnection(connetionString)
connection = New MySqlConnection(ConfigurationManager.ConnectionStrings("xCollectibles.My.MySettings.xcollectiblesConnectionString").ToString)
Try
connection.Open()
command = New MySqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "id"
ComboBox1.DisplayMember = "value"
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
Thanks you..

Get specific row col values from mysql using vb 2012

I have one button retrieve I just want to get the database table "account" value by its row and col and display it in a textbox. I keep on getting errors on the datafill line
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dataset As DataSet
Dim datatable As DataTable
Dim sqlcon As MySqlConnection
Dim dataadapter As MySqlDataAdapter
Dim sqlcommand As MySqlCommand
Dim sql As String
Private Sub retrieve_Click(sender As Object, e As EventArgs) Handles retrieve.Click
sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")
sqlcon.Open()
sql = "select * from account"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataadapter.Fill(dataset)
TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Sub
End Class
You need to instantiate the dataset that you pass to the Fill method.
....
dataset = new DataSet()
dataadapter.Fill(dataset)
...
Do not forget to close the connection when finished. It is a resource very costly to keep open when you not need it
Using sqlcon = New MySqlConnection("Data Source=localhost;Database=database;User ID=root;Password=;")
sqlcon.Open()
sql = "select * from account"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataset = new DataSet()
dataadapter.Fill(dataset)
TextBox2.Text = dataset.Tables(0).Rows(0).Item(0).ToString()
End Using
See the Using Statement
However if you need only one row it is better to refine the query applying a WHERE clause to limit the results returned by the database.
sql = "select * from account WHERE AccountName = #name"
dataadapter = New MySqlDataAdapter(sql, sqlcon)
dataadapter.SelectCommand.Parameters.AddWWithValue("#name", inputNameBox.Text)
dataset = new DataSet()
dataadapter.Fill(dataset, "Account")
if dataset.Tables("Account").Rows.Count > 0 then
TextBox2.Text = dataset.Tables("Account").Rows(0).Item(0).ToString()
End If
this hopefully will return just the row needed

Could string variable in vb.net be a reference in SQL Where statement?

Could anyone help me with the following WHERE statement ? I want to make bn as reference in WHERE statement.
This is whats in my code:
Public bn As String = ""
Dim SQLStatement As String = "UPDATE patient SET number_of_bottles='" & lblBottle.Text & "' WHERE bednumber=bn ORDER BY patient_ID DESC LIMIT 1"
During the program, bn is an identifier where I would know which bednumber I will gonna access.
Any help would be appreciated thanks!
(Edited to use MySQL-specific objects rather than generic ODBC)
Dim bn As String = "" ' Set this to some value in your code
Dim bottles As Integer = 0 ' Set this to some value in your code
Dim SQLStatement As String = "UPDATE patient SET number_of_bottles = #bottles WHERE bednumber = #bednumber"
Using cnn As New MySqlConnection("Connection string here")
Dim cmd As New MySqlCommand(SQLStatement, cnn)
cmd.Parameters.AddWithValue("bottles", bottles)
cmd.Parameters.AddWithValue("bednumber", bn)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
End Using
Alternate version, creating MySqlParameter objects by hand -- note that you'll need to create the parameter objects, set their values, then add them to the parameters collection of the MySqlCommand object
Using cnn As New MySqlConnection("Connection string here")
Dim cmd As New MySqlCommand(SQLStatement, cnn)
Dim pBottles As New MySqlParameter("bottles", bottles)
Dim pBedNumber As New MySqlParameter("bednumber", bn)
cmd.Parameters.Add(pBottles)
cmd.Parameters.Add(pBedNumber)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
End Using