Populate a combobox with tables of a database in VB - mysql

I want to populate my combobox with the name of the tables of my database "converter" that has 3 tables. I'm using the following code:
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
command.Connection = conn
command.CommandText = "SHOW TABLES"
adapter = New MySqlDataAdapter(command.CommandText, conn)
adapter.SelectCommand = command
adapter.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "column_name"
ComboBox1.ValueMember = "column_name"
Catch ex As Exception
End Try
This code populates 3 items inside the combobox (which is the same as the number of tables inside my database). But what shows is this:
How can I populate my combobox with the exact name of my tables and not like this? I tried putting .toString on my dt but it's no good.
Can anyone help me? Thank you in advance. :)
EDIT
I used Steve's method and I was able to get the values. I used this code.
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
command.Connection = conn
command.CommandText = "SHOW TABLES"
adapter = New MySqlDataAdapter(command.CommandText, conn)
adapter.SelectCommand = command
dt = conn.GetSchema("TABLES")
adapter.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "table_name"
ComboBox1.ValueMember = "table_name"
Catch ex As Exception
End Try
But now it shows 3 additional empty values. refer to this image:

If I am right the correct values to pass to your combobox DisplayMember and ValueMember is
Tables_in_converter
In other words, the name of the only column returned by your command is built automatically using the fixed text "Tables_in_" followed by the <databasename>
If you want to use a different approach you could call the GetSchema method of the connection object in this way
using cnn = new MySqlConnection(...)
cnn.Open()
Dim dt = cnn.GetSchema("TABLES")
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "table_name"
ComboBox1.ValueMember = "table_name"
End Using

Related

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..

VB.NET ComboBox SelectedIndex from MySQL

so I have done with show data form my database MySQL to ComboBox.. I'm using this code:
Private Sub Get_Product()
Connection()
Dim command As New MySqlCommand
Dim reader As MySqlDataReader
Dim query As String = "SELECT * FROM product, writer, publisher WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND code = " & throwCode & " ORDER BY code"
Dim queryWriter As String = "SELECT DISTINCT writer, writer_name FROM writer ORDER BY writer_name"
Dim dataAdapter As New MySqlDataAdapter(queryWriter, conn)
Dim dataSet As New DataSet
dataAdapter.Fill(dataSet, "writer")
Try
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
While reader.Read
TextBoxISBN.Text = reader("isbn")
TextBoxTitle.Text = reader("title")
TextBoxPage.Text = reader("page")
With (ComboBoxWriter)
.Items.Add("Select")
.DataSource = dataSet.Tables("writer")
.DisplayMember = "writer_name"
.ValueMember = "writer"
.SelectedIndex = 0 **// Give atention to this code**
End With
TextBoxYear.Text = reader("year")
TextBoxCategory.Text = reader("category")
TextBoxCallNumber.Text = reader("call_number")
TextBoxWeight.Text = reader("weight")
TextBoxPurchasePrice.Text = reader("purchase_price")
TextBoxSellingPrice.Text = reader("selling_price")
TextBoxDiscount.Text = reader("discount")
TextBoxDescription.Text = reader("description")
TextBoxTag.Text = reader("tag")
TextBoxPusatPenerbit.Text = reader("pusat_penerbit")
TextBoxMrican.Text = reader("mrican")
TextBoxPaingan.Text = reader("paingan")
If (Not IsDBNull(reader("picture"))) Then
Dim byteImage() As Byte = reader("picture")
Dim tempImage As New System.IO.MemoryStream(byteImage)
PictureBoxPicture.Image = Image.FromStream(tempImage)
End If
End While
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
In my code, I give some comment and bold to show you what I want to do.
So I have a writer code in product an writer code in writer (writer code named as writer), and I join the table to show writer name from writer code. But in ComboBox I want to show all of writer for editing but the default value is index of the writer that same like in product table.
1
2
If you see my first image that have a writer name Sutarjo Adisusilo but when I view it and want to use it as a default value in combobox that show A. Kardiyat Wiharyanto as indexvalue number 0..
I need help how to change the default value to be same like the picture number 1
Thanks
I've updated this answer to an easier method. Double check the column names though.
ComboBoxWriter.SelectedIndex = ComboBoxWriter.FindStringExact(reader("writer_name"))

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. :)

Need help filling datagrid from MySQL

I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try
You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).

vb.net mysql combobox show tables

I am new at programming, and I'm working on a basic VB.NET application that allows the user to select, insert, update, and delete various data tables from MySQL.
The trouble I'm having is, I need to populate a combobox with all the table names from one specific database, so that the user can select which database table to work with. I thought my code would work, but all I'm getting when I run the app is a blank combobox.
Could someone please tell me what's wrong with my code?
Thanks so much in advance!
Code:
Private Sub TableList_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles TableList.SelectedIndexChanged
Try
command = New MySqlCommand
dt = New DataTable
adapter = New MySqlDataAdapter
If (conn.State = ConnectionState.Closed) Then
setConnection()
End If
command.Connection = conn
command.CommandText = "SHOW TABLES"
adapter.SelectCommand = command
reader = command.ExecuteReader
'adapter.Fill(dt)
dt.Load(reader)
TableList.DataSource = dt
TableList.DisplayMember = "Tables_in_sampledata" 'What is displayed
TableList.ValueMember = "Tables_in_sampledata" 'The ID of the row
Catch ex As MySqlException
MessageBox.Show("Error1: " & ex.Message)
Finally
reader.Close()
conn.Close()
End Try
End Sub
Instead of SHOW TABLES, use the following query
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='YourDatabase';