Hide part of String.Format within a ComboBox.Item - mysql

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

Related

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

vb 2010 mysql insert record operation inserts a blank record but no data is inserted

I am trying to develop a utility in vb 2010, which will store values from Datagridview control to a mysql table
Steps
1) Datagrid cell values are stored in an array
2) Array values are used .AddWithValue() function
Present status: Only a blank record is inserted. Data is missing.
Please refer to following code.
Function insertRec()
'dgExistingProject is datagridview control embedded on the form
Dim ServerString As String = "Server=pnserver;User ID=root;
Password=; Database=prayer_net"
Dim Arr(RCount) As String
Dim SQLConn As MySqlConnection = New MySqlConnection
SQLConn.ConnectionString = ServerString
dim I as Integer
For I = 0 To RCount
Arr(I) = dgExistingProject.Rows(I).Cells(1).Value
Next
Try
Dim dt As Date = DateTime.Now.ToString("yyyy/MM/dd
HH:mm:ss")
Dim projName as Integer=Arr(4)
Using sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = "INSERT INTO dyn_dwg_register
(file_name,file_location,dwg_description,
project_id,created_by, created_on)" & _
" values (#file_name, #file_location, #dwg_description, #project_id, #created_by, #created_on)"
.CommandType = CommandType.Text
.Connection = SQLConn
.Parameters.AddWithValue("#file_name", Arr(0))
.Parameters.AddWithValue("#file_location", Arr(1))
.Parameters.AddWithValue("#dwg_description", Arr(2))
.Parameters.AddWithValue("#project_id", ProjName)
.Parameters.AddWithValue("#created_by", Arr(4))
.Parameters.AddWithValue("#created_on", dt)
End With
Try
SQLConn.Open()
If SQLConn.State = ConnectionState.Open Then
Dim ID As Integer = sqlCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConn.Close()
End Try
End Using
Catch e As Exception
MsgBox (e.Message.ToString)
End Try
End Function
Rajendra Nadkar
i had written a code in C# where i had to store data from a datagrid to SQL database. I used the following code. I think it will help you.
string sqlquery = "UPDATE TableName set ColumnName1=#param1 where ColumnName2=#param2";
using (OleDbCommand Cmd = new OleDbCommand(sqlQuery, dbCon))
{
Cmd.Parameters.AddWithValue("#param1", Convert.ToDouble(dataGridView1[1, index].Value));
Cmd.Parameters.Add(new OleDbParameter("#param2", OleDbType.VarWChar)).Value = "somevalue";
updateDbCmd.ExecuteNonQuery();
updateDbCmd.Parameters.Clear();
}
Funny, I changed the field name prefix # to ? and things became smooth. In an earlier question in Feb 11, Stelian Matei suggested this edit, though later on Giezel Esteves reversed it. (Original question asked by user1176607 in Feb '10)
I guess I need to refer to documentation more thoroughly. Anyways I am giving the working code here if you or anybody interested in it.
Dim qry As String = "INSERT INTO dyn_dwg_register (`file_name` , `file_location`, `dwg_description`, `project_id`, `created_by`)" & _
" values (?file_name, ?file_location, ?dwg_description, ?project_id, ?created_by)"
Dim sqlCommand As MySqlCommand
sqlCommand = New MySqlCommand(qry, SQLConn)
sqlCommand.CommandType = CommandType.Text
With sqlCommand
.Parameters.AddWithValue("?file_name", Arr(0))
.Parameters.AddWithValue("?file_location", Arr(1))
.Parameters.AddWithValue("?dwg_description", Arr(2))
.Parameters.AddWithValue("?project_id", ProjName)
.Parameters.AddWithValue("?created_by", Arr(2))
End With

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

Loop through Database table and get all values of each record in turn

I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub

vb.net/mysql show more then 1 row in TextBox

I just started messing around with Visual basic (vb.net) and am trying to show more then 1 database row in a TextBox, so far I have this:
Private Sub foobox_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = connStr
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim myAdaptor As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdaptor.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
If myData.HasRows Then
myData.Read()
Viewer.Text = myData("foo1") & myData("foo2")
End If
myData.Close()
conn.Close()
End Sub
which connects to a database successfully but but it only outputs 1 row, how can I get it to output more?
You need a loop reading data and storing line after line in a StringBuilder.
Then, when exiting from the reading loop set the Text property of your textbox
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
and, of course, your textbox should have the MultiLine property set to True
Apart from this direct answer to your question, your code should be changed to dispose the connection and the datareader after use, I have also removed the DataAdapter because is not needed here
Using conn = New MySqlConnection(connStr)
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New SqlCommand(sqlquery, conn)
Using myData = myCommand.ExecuteReader()
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
End Using
End Using
You need some kind of loop. I would also use the Using statement to ensure that all unmanaged resources are disposed even in case of an exception(it also closes the connection):
Using conn As New MySqlConnection(connStr)
Using myCommand As New MySqlCommand("SELECT * FROM foo ORDER BY id DESC", conn)
Try
conn.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim line = String.Format("{0}{1}{2}",
myData.GetString(myData.GetOrdinal("foo1")),
myData.GetString(myData.GetOrdinal("foo1")),
Environment.NewLine)
viewer.Text &= line
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
End Using
However, if you want to show multiple records i would recommend a ListBox instead. It's more efficient with many items and it also separates them logical from each other.
( just replace viewer.Text &= line with ListBox1.Items.Add(line) )