How to display data from mysql base from Dropdownlist selection - mysql

i want to display mysql data base from the dropdownlist. i populate data from dropdownlist using this code and it works perfectly. in this code it will show the productnames in the dropdownlist
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT tbl_productid,tbl_productname FROM tbl_products")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
cmbProducts.DataSource = cmd.ExecuteReader()
cmbProducts.DataTextField = "tbl_productname"
cmbProducts.DataValueField = "tbl_productid"
cmbProducts.DataBind()
con.Close()
End Using
End Using
cmbProducts.Items.Insert(0, New ListItem("Select Product"))
End If
Now base from the selected product name i want to display its productID to textbox. but this code gives me no output? i dont know what is wrong with my code anyone who can help me
This is code
Protected Sub cmbProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cmbProducts.SelectedIndexChanged
'MsgBox("Hellow World!", MsgBoxStyle.Critical)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim con As New MySqlConnection(constr)
con.Open()
Dim cmd As New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '" + cmbProducts.Text + "'", con)
Dim sda As New MySqlDataAdapter(cmd)
'Dim dr As New MySqlDataReader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read Then
txtProductID.Text = dr.GetValue(0)
End If
con.Close()
con.Dispose()
End Sub

Ok, a few things.
The drop list has two columns. data value (id), and data text.
What you have looks good.
However, when you get/grab/use the drop list, then you have this:
DropDownList1.Text - this will return the data value (1st column)
DropDownList1.SelectedValue - this will ALSO return data value (1st column)
DropDownList1.SelectedItem.Text - this gets the 2nd display text value (2nd column)
So, because a LOT of drop lists can be only one column, then the .text and .SelectedValue can both be used. (in other words, you can use .text, but it gets the first value, and since a lot of drop lists might only have one column, then .text always gets that first value). But I would consider the habit of SelectedValue for the column that drives the drop list.
In your case, you really do want the 2nd column, and thus you want to use:
DropDownList1.SelectedItem.Text
So,
New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '"
+ cmbProducts.SelectedItem.Text + "'", con)

I used my own data to demonstrate. Also I used given control names in my test program. This is not what your want to do in your application. Your control names are good.
I broke the code into the data access part and the user interface code. There is very little code in the actual event procedure.
You have set the .DataValueField to the id so you can retrieve that value in the SelectedIndexChanged event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillDropDownList()
End If
End Sub
Private Sub FillDropDownList()
Dim dt = GetListBoxData()
DropDownList1.DataTextField = "Name"
DropDownList1.DataValueField = "ID"
DropDownList1.DataSource = dt
DropDownList1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim dt = New DataTable
Dim Query = "Select Top 10 ID, Name
FROM Coffees;"
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(Query, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
TextBox1.Text = DropDownList1.SelectedValue
End Sub
There is no need to make a second round trip to the database. You already have the data you require.

Related

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

Adding a record in Datagridview Row in Vb.net

Hello I have Datagridview in my vb.net form and i want to display the data from the MySQL table to the Datagridview (Dgv) of Vb.net but the problem is when i update or delete an record in Dgv the current record that i fetch is adding more display of the current record. I write this code like this because I'm going to add more function on it, I know i can do this using MySqlDataAdapter and DataSet then fill the datagridview of this code but i use this to add more function, for now how can i update/delete an record without adding more rows that i currently fetch. or doubling the row's
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
Dim row() As String
row = new String() {empId, empName, empAddress}
DataGridView1.Rows.Add(row)
End While
reader.close()
cmd.close()
I know the problem is in Rows.Add
Added:
Currently the function of this is to display the data and when event or button was click this Sub will be called again. with out adding more display.
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
'before adding new row in datagridview add this code
DataGridView1.Rows.clear();
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
so that it will remove the old value of the row and then add the new value in the database
This should do what you want. You can easily select from sql server to datagridview, change data, and pass change from datagridview to sql server.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source='your_server';Initial Catalog='your_database';Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

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

Having issues with pulling data to a listbox, MySQL to VB.Net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim conn As New MySqlConnection("server=localhost;user=root;password=Password;database=giordydatabase")
conn.Open()
Dim command As New MySqlCommand("SELECT firstName, lastName FROM student ORDER BY firstName;")
Dim dataSet As New DataSet()
Dim dataAdapter As New MySqlDataAdapter()
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataSet, "student")
Dim dataTable As DataTable = dataSet.Tables("student")
For Each row As DataTable In dataTable.Rows
Dim newStudent As New Student
newStudent.strFirstName = row.Item("firstName")
newStudent.strLastName = row.Item("lastName")
Dim mainStudentList As Object = Nothing
mainStudentList.add(newStudent)
lstStudents.item.add(newStudent.nameConcat)(newStudent.strFirstName, strLastName)
Next
Catch ex As Exception
MsgBox("Error " & ex.ToString())
Finally
conn.Close()
End Try
End Sub
I have an issue as I would like to connect my database to the listbox, also would like it to pull data only the first name and last name data and combine the two to create a name for a list for students to select themselves. But the code above isn't allowing me to do this.
Note the list box is only there for user selection and once they select themselves the they can use the application under the name they selected.
Your problem seems to be the fact that you are setting your main students list to type object and as nothing...
Try to move this line
Dim mainStudentList As Object = Nothing
out of where it is nested and move it so that it is the FIRST line in your code block...
Also instead of what you got currently in that line, change it to...
Dim mainStudentList As Generic.List(Of Student)
Finally change this line...
lstStudents.item.add(newStudent.nameConcat)(newStudent.strFirstName, strLastName)
to ...
lstStudents.item.add(Trim(newStudent.strFirstName) & " " & Trim(newStudent.strLastName))
Try that and see what happens, Good luck.

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