I have a DataBound DGV it has 3 Columns namely ID(not pk), Name, and Status. I have 2 Buttons Add and Post. Add, adds Data to the DGV and DataBase(MySql) but in Status, it adds "No". What I want to do is for example I have 3 Rows in my DGV and highlight those 3 and click Post, the value in Status will be changed to "Yes". Here is what I have done so far, but I'm having trouble with the syntax for the UPDATE QUERY. THIS CODE WORKS NOW
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the TestDataSet.testing table. You can move, or remove it, as needed.
Me.TestingTableAdapter.Fill(Me.TestDataSet.testing)
Using _conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using cmd
With cmd
MsgBox("Connection Established")
.Connection = _conn
.Parameters.Clear()
.CommandText = "Select Max(TransactionID) from testing"
_conn.Open()
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader()
If dr.Read() Then
If IsDBNull(dr.Item(0)) Then
txtNumber.Text = "1"
Else
txtName.Text = dr(0).ToString() + 1
End If
End If
End With
End Using
End Using
FillGrid()
End Sub
Private Sub FillGrid()
Using _conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using _comm As New MySqlCommand
With _comm
.CommandText = " SELECT `ID`, `TransactionID`, `Name`, `Posted` FROM `testing`"
.Connection = _conn
End With
Using _adapter As New MySqlDataAdapter(_comm)
Try
_conn.Open()
Dim _ds As New DataSet
_adapter.Fill(_ds)
GVTransaction.DataSource = _ds.Tables(0)
Catch ex As Exception
End Try
End Using
End Using
End Using
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Using conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using cmd
With cmd
MsgBox("Connection Established")
.Connection = conn
.Parameters.Clear()
.CommandText = "INSERT INTO testing(TransactionID, Name, Posted) VALUES (#ID, #iName, #iPosted)"
.Parameters.Add(New MySqlParameter("#ID", txtNumber.Text))
.Parameters.Add(New MySqlParameter("#iName", txtName.Text))
.Parameters.Add(New MySqlParameter("#iPosted", "No"))
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString())
End Try
End Using
End Using
MsgBox("Data Added to the Database")
Me.TestingTableAdapter.Dispose()
Me.TestingTableAdapter.Fill(Me.TestDataSet.testing)
End Sub
Private Sub btnPost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPost.Click
Dim _ID As New List(Of String)
Dim _Name As New List(Of String)
For Each _x As DataGridViewRow In TestingDataGridView.SelectedRows
_ID.Add(_x.Cells("GVTransactionID").Value.ToString())
_Name.Add("'" & _x.Cells("GVName").Value.ToString() & "'")
Next
Dim inClause As String = String.Join(",", _ID.ToArray())
Dim inClause1 As String = String.Join(",", _Name.ToArray())
Dim _sqlUpdate As String = String.Format("UPDATE testing SET Posted = #Posted WHERE TransactionID IN ({0}) AND Name IN ({1})", inClause, inClause1)
Using _conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using _commm As New MySqlCommand()
With _commm
.CommandText = _sqlUpdate
.Connection = _conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("#Posted", "YES")
End With
Try
_conn.Open()
_commm.ExecuteNonQuery()
FillGrid()
Catch ex As MySqlException
MsgBox(ex.StackTrace.ToString)
End Try
End Using
End Using
End Sub
End Class
Any Helps or tips is greatly appreciated. Please and Thank you
Try this one,
Dim _ID As New List(Of String)
Dim _Name As New List(Of String)
For Each _x As DataGridViewRow In TestingDataGridView.SelectedRows
_ID.Add(_x.Cells("TransactionID").Value.ToString())
_Name.Add("'" & _x.Cells("Name").Value.ToString() & "'")
Next
Dim inClause As String = String.Join(",", _ID.ToArray())
Dim inClause1 As String = String.Join(",", _Name.ToArray())
Dim _sqlUpdate As String = String.Format("UPDATE testing SET Posted = #Posted WHERE TransactionID IN ({0}) AND Name IN ({1})", inClause, inClause1)
Using _conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = test")
Using _comm As New MySqlCommand()
With _comm
.CommandText = _sqlUpdate
.Connection = _conn
End With
Try
_conn.Open()
_comm.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString())
End Try
End Using
End Using
I believe you can simply use this
For Each Row As DataGridViewRow In TestingDataGridView.SelectedRows
.CommandText = "UPDATE testing SET Posted = #iChange WHERE ID = " & Row.Cells(0) & ", Name = " & Row.Cells(1)
.CommandType = CommandType.Text
.Parameters.AddWithValue("#iChange", "Yes")
End For
Hope this helps :)
Related
I have a textbox, button, and datagridview in my form. When i click the button, system will grab a table depending on my textbox from the database and show on datagridview.
I getting this error when i click the button. Where am I wrong?
here is my dbconn
Module mod_dbconn
Public conn As MySqlConnection
Public Sub openDB()
Dim dbname As String = scr_sales.btn_dbswitch.Text
Dim server As String = "localhost"
Dim user As String = "root"
Dim password As String = ""
Try
conn = New MySqlConnection
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, user, password, dbname)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This is my form
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim query As String = "SELECT * FROM '" + TextBox1.Text + "'"
Dim cmd As New MySqlCommand(query, conn)
Dim da As New MySqlDataAdapter(cmd)
Dim dt = New DataTable
Dim cb As MySqlCommandBuilder
cb = New MySqlCommandBuilder(da)
DataGridView1.Refresh()
Try
conn.Open()
da.Fill(dt)
Dim bsource As New BindingSource
bsource.DataSource = dt
Me.DataGridView1.DataSource = bsource
da.Update(dt)
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
You are trying to build a dynamic table select so for the table name you don't need the quotes around the tablename
"SELECT * FROM " + TextBox1.Text + " ;"
I have a form in which data gets insert. There are some checkboxlist. CheckboxList binds with table in db. Now after selecting items it should enter selected values in db table but it inserts empty strings.
I have two checkboxlist (products, payment) Payment works fine. problem is in products.
VB code
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateProducts()
Me.PopulatePayments()
End Sub
Private Sub PopulateProducts()
productsList.Items.Clear()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from chemistsProducts"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("productName").ToString()
item.Value = sdr("productName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
productsList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
productsList.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub PopulatePayments()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from payment"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("paymentName").ToString()
item.Value = sdr("paymentID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
ListPayment.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
ListPayment.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub save_Click(sender As Object, e As EventArgs) Handles save.Click
Dim selectedProducts As String = String.Empty
For Each chk As ListItem In productsList.Items
If chk.Selected = True Then
selectedProducts &= "<li>" + chk.Text + "</li>"
End If
Next
Dim payments As String = String.Empty
For Each chk As ListItem In ListPayment.Items
If chk.Selected = True Then
payments &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO chemists (`products`, `payment`) values ('" + selectedProducts + "', '" + payments + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Here Payment gets inserted what I have selected. Problem is in selectedProducts
Try below in page load,
If Not IsPostBack Then
Me.PopulateProducts()
Me.PopulatePayments()
End If
This button filters the datagridview using datetimepicker.
What should I do if I want to filter it between dates?
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "Server = Localhost; database = venuesdb; user id = root; Password = "
Dim SQLDataAdapter As New MySqlDataAdapter
Dim DatabaseDatSet As New DataTable
Dim Bindsource As New BindingSource
Try
MySqlConn.Open()
Dim Query = "Select * From venuesdb.cost where EventDate = ('" & DateTimePicker1.Text & "')"
Command = New MySqlCommand(Query, MySqlConn)
SQLDataAdapter.SelectCommand = Command
SQLDataAdapter.Fill(DatabaseDatSet)
Bindsource.DataSource = DatabaseDatSet
DataGridView1.DataSource = Bindsource
SQLDataAdapter.Update(DatabaseDatSet)
MySqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MySqlConn.Dispose()
End Sub
I'm almost done with a trial program where I add, edit and delete stuff from my MySQL database.
But I can't seem to make the delete button to work.
Here's my code for the Delete Button:
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
The ERROR
http://stivigan.us.to/images/delete_error.jpg
And here's the rest of my Main Form.
Imports MySql.Data.MySqlClient
Public Class frm_main
Public sConnection As New MySqlConnection
Public IDNo As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM tbl_adbms_test"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
list_view_people.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With list_view_people
.Items.Add(TABLE.Rows(i)("IDNo"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("LastName"))
.Add(TABLE.Rows(i)("FirstName"))
End With
End With
Next
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_add.Click
frm_add.ShowDialog()
End Sub
Private Sub btn_modify_Click(sender As Object, e As EventArgs) Handles btn_modify.Click
If IDNo = Nothing Then
MsgBox("Please choose a record to modify.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT LastName, FirstName FROM tbl_adbms_test WHERE IDNo='" & list_view_people.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
frm_modify.IDNo = list_view_people.SelectedItems(0).Text
frm_modify.LastName = sqlTable.Rows(0)("LastName")
frm_modify.FirstName = sqlTable.Rows(0)("FirstName")
frm_modify.ShowDialog()
End If
End Sub
Private Sub list_view_people_MouseClick(sender As Object, e As MouseEventArgs) Handles list_view_people.MouseClick
IDNo = list_view_people.SelectedItems(0).Text
End Sub
Private Sub btn_delete_Click(sender As Object, e As EventArgs) Handles btn_delete.Click
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
End Sub
End Class
Add Form
Public Class frm_add
Public sConnection As New MySqlConnection
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO tbl_adbms_test(IDNo,LastName,FirstName) VALUES(NULL,'" & txt_last_name.Text & "','" & txt_first_name.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("The data was saved.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Edit Form
Imports MySql.Data.MySqlClient
Public Class frm_modify
Friend IDNo As Integer
Friend LastName As String
Friend FirstName As String
Public sConnection As New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txt_last_name.Text = LastName
txt_first_name.Text = FirstName
End Sub
Private Sub btn_update_Click(sender As Object, e As EventArgs) Handles btn_update.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "UPDATE tbl_adbms_test SET LastName='" & txt_last_name.Text & "', FirstName='" & txt_first_name.Text & "' WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Thanks in advance. :)
You don't have the connection open before executing the Delete command.
This is a common scenario when you keep a global connection object around in your code.
You gain nothing and there are always situations in which you end with the connection in a wrong state
You could write
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
if sConnection.ConnectionState = ConnectionState.Closed Then
sConnection.Open
End If
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
but I really suggest to remove your usage of the global connection object and replace it with a local MySqlConnection that will be created just when you use it and closed/destroyed after the usage. This is the intended usage of the Using Statement
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
Using con = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(sqlQuery, con)
con.Open
With cmd
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
End Using
End Using
Notice also that I have removed the string concatenation in your sqlQuery and used a safer parameterized approach (albeit in this scenario and if the ListView is not editable there are no real risk of sql injection)
What is wrong in this code
I run the software click the button and nothing happens if you have a better code that would help thanks in advance
Dim sql As String
Dim con As MySqlConnection = New
MySqlConnection("Server=localhost;Database=******;Uid=*****;password =******")
Dim ds As DataSet = New DataSet
Dim dataadapter As MySqlDataAdapter = New MySqlDataAdapter
Dim cmd As MySqlCommand = New MySqlCommand()
Dim datareader As MySqlDataReader
Try
sql = "SELECT * FROM users"
con.Open()
cmd.CommandText = sql
cmd.Connection = con
dataadapter.SelectCommand = cmd
datareader = cmd.ExecuteReader
While datareader.Read
datareader.Read()
Email.Text = datareader("Email")
LastName.Text = datareader("LastName")
Address.Text = datareader("Address")
End While
Catch ex As Exception
End Try
con.Close()
End Sub
Narrow the scope of your select. The way its written I think it might set the textbox 100 times if 100 results are returned. Here is how I would write this:
Imports MySql.Data.MySqlClient
Public Sub getData()
Dim objConn As MySqlConnection = New MySqlConnection("Data Source=localhost;" _
& "Database=TestDB;" _
& "User ID=Root;" _
& "Password=myPassword;")
Dim strSQL As String = "SELECT TOP 1 Email, LastName, Address FROM users"
Dim da As MySql.Data.MySqlClient.MySqlDataAdapter
Dim dt As New DataTable
Try
objConn.Open()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(strSQL, objConn)
da.Fill(dt)
If dt.Rows.Count > 0 Then
Email.Text = dt.Rows(0)("Email").ToString
LastName.Text = dt.Rows(0)("LastName").ToString
Address.Text = dt.Rows(0)("Address").ToString
End If
da = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
objConn.Close()
objConn = Nothing
End Try
End Sub