i have this 3 Forms in my project, on the second Form i have this edit button where i will edit the Listview item on the third Form, but when i select an item in the Listview and press edit, an error shows. It took me hours to find what's the problem, and i ended up here. Am i missing something?
this is my first form with listview in it.
Imports MySql.Data.MySqlClient
Public Class Form5
Public cd As Integer
Dim con As MySqlConnection
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New MySqlConnection
con.ConnectionString = "server=localhost;user id=root;database=db;password=root"
con.Open()
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sConnection As New MySqlConnection
sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
sConnection.Open()
Dim sqlQuery As String = "select * from candidate where cfname<>'Select a Candidate' AND candidacy='Filed'"
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
LvPeople.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With LvPeople
.Items.Add(TABLE.Rows(i)("idn"))
With .Items(.Items.Count - 1).SubItems
.Add(AddFieldValue(TABLE.Rows(i), ("cpos")))
.Add(AddFieldValue(TABLE.Rows(i), ("cfname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cmname")))
.Add(AddFieldValue(TABLE.Rows(i), ("clname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cparty")))
End With
End With
Next
End Sub
Private Function AddFieldValue(ByVal row As DataRow, ByVal fieldName As String) As String
If Not DBNull.Value.Equals(row.Item(fieldName)) Then
Return CStr(row.Item(fieldName))
Else
Return Nothing
End If
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form17.Show()
End Sub
End Class
my 2nd Form
Imports MySql.Data.MySqlClient
Public Class Form17
Public cd As Integer
Public sConnection As New MySqlConnection
Private Sub Form17_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
sConnection.Open()
End If
LoadPeople3()
End Sub
Public Sub LoadPeople3()
Dim sqlQuery As String = "select * from candidate where cfname<>'Select a Candidate'"
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
lvPeople3.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With lvPeople3
.Items.Add(TABLE.Rows(i)("idn"))
With .Items(.Items.Count - 1).SubItems
.Add(AddFieldValue(TABLE.Rows(i), ("cfname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cmname")))
.Add(AddFieldValue(TABLE.Rows(i), ("clname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cyr")))
End With
End With
Next
End Sub
Private Function AddFieldValue(ByVal row As DataRow, ByVal fieldName As String) As String
If Not DBNull.Value.Equals(row.Item(fieldName)) Then
Return CStr(row.Item(fieldName))
Else
Return Nothing
End If
End Function
Private Sub lvPeople3_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvPeople3.MouseClick
cd = lvPeople3.SelectedItems(0).Selected
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If cd = Nothing Then
MsgBox("Please choose a record to edit.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT * FROM candidate WHERE cid = '" & lvPeople3.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTabble As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTabble)
End With
Form23.cd = lvPeople3.SelectedItems(0).Text
Form23.cfname = sqlTabble.Rows(0)("cfname")
Form23.cfname = sqlTabble.Rows(0)("cmname")
Form23.cfname = sqlTabble.Rows(0)("clname")
Form23.ShowDialog()
cd = Nothing
End If
End Sub
End Class
and my third Form
Imports MySql.Data.MySqlClient
Public Class Form23
Friend cd As Integer
Friend cfname As String
Friend clname As String
Friend cmname As String
Public sConnection As New MySqlConnection
Private Sub Form23_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
sConnection.Open()
End If
TextBox2.Text = cfname
TextBox3.Text = clname
TextBox4.Text = cmname
End Sub
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = conn
conn.Open()
If TextBox1.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Dim sqlQuery As String = "UPDATE candidate SET cpos='" & ComboBox1.Text & "', cparty='" & TextBox1.Text & "', candidacy='Filed' WHERE cid='" & cd & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record Updated")
Dispose()
Form5.Show()
Form17.Hide()
End If
Form5.LoadPeople()
Form17.LoadPeople3()
Me.Close()
End Sub
End Class
In Button1_Click you are accessing the first DataRow of a DataTable without checking if there is one:
Form23.cfname = sqlTabble.Rows(0)("cfname")
Form23.cfname = sqlTabble.Rows(0)("cmname")
Form23.cfname = sqlTabble.Rows(0)("clname")
You can check if there is one row by using the DataTable.Rows property:
If sqlTabble.Rows.Count > 0 Then
Form23.cfname = sqlTabble.Rows(0)("cfname")
Form23.cfname = sqlTabble.Rows(0)("cmname")
Form23.cfname = sqlTabble.Rows(0)("clname")
End If
Since you are trying to get all records according to the user's selection, i guess that you're using the wrong field. You are using the display-field but you are filtering by the ID-field:
"SELECT * FROM candidate WHERE cid = '" & lvPeople3.SelectedItems(0).Text & "'"
Maybe this is what you actually want:
"SELECT * FROM candidate WHERE cfname = '" & lvPeople3.SelectedItems(0).Text & "'"
Note that you should not use string concatenation but sql-parameters to prevent sql injection.
Related
Private Sub delivery_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sel.Items.Add("allitems")
MsgBox("alert")
Me.EntryTableAdapter.Fill(Me.TailerDataSet.entry)
viewdata.Visible = False
ConnectionState = "Data Source=SWTEAM-II-5\SQLEXPRESS;Initial Catalog=tailer;User ID=sa;Password=123"
con = New SqlConnection(ConnectionState)
con.Open()
Dim sqlquery As String
sqlquery = "Select p_name from entry"
cmd = New SqlCommand(sqlquery, con)
Dim rd As SqlDataReader = cmd.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rd)
dt.Rows.Add("allitems")
sel.ValueMember = "p_name"
sel.DisplayMember = "p_name"
sel.DataSource = dt
only combobox showing db values not manual values
Dim sqlquery As String
sqlquery = "Select p_name from entry"
cmd = New SqlCommand(sqlquery, con)
Dim adapter As New SqlDataAdapter(cmd)
sel.Items.Add("allitems")
Dim dap As New SqlDataAdapter("SELECT * FROM entry", con)
Dim ds As New DataSet
dap.Fill(ds)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
sel.Items.Add(ds.Tables(0).Rows(i).Item("p_name"))
Next
Imports MySql.Data.MySqlClient
Public Class home1
Dim id As String
Dim name1 As String
Dim name2 As String
Dim address As String
Dim age As Integer
Dim gender As String
Dim bday As Date
Dim height1 As String
Dim weight1 As String
Dim crimcase As String
Dim eye As String
Dim con As New MySqlConnection
Dim source1 As New BindingSource()
Dim source2 As New BindingSource()
Dim ds As DataSet = New DataSet
Dim tables As DataTableCollection = ds.Tables
Private Sub home1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = "Server=localhost;User Id=root;Password='';Database=db_criminalrecord"
Catch ex As Exception
MsgBox(ex.Message)
End Try
fill()
End Sub
Public Sub fill()
Dim dt As New DataTable
Dim str As String = "SELECT ID,Criminal_Name,Alias,Address,Age,Gender,Height,Weight,Date_of_Birth,criminal_Case,Eye_Colour "
Dim da As New MySqlDataAdapter(str, con)
da.Fill(dt)
da.Dispose()
source1.DataSource = dt
DataGridView1.DataSource = dt
DataGridView1.Refresh()
DataGridView1.Columns(13).Width = 150
End Sub
Sub clear()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
TextBox9.Text = ""
TextBox10.Text = ""
End Sub
End Class
Your select statement is not containing FROM TABLE_NAME part.
I have problem when i'm trying to fetch data from mysql database
I always get the last record.
How can I get all records showing on the datagridview synchronously
Here is my code
Please can someone help me
Public Class Form1
Private RowCount As Integer = 0
Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ListBox1.Items.Add(e.UserState)
ProgressBar1.Value = e.ProgressPercentage
Label1.Text = "Processing row.. " + e.ProgressPercentage.ToString()
DataGridView1.Rows.Add(New Object() {f1, f2})
Me.ProgressBar1.Maximum = RowCount
End Sub
Dim ListText As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles go.Click
go.Enabled = False
cancel.Enabled = True
ListBox1.Items.Clear()
ProgressBar1.Value = 0
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.RunWorkerAsync()
Me.Cursor = Cursors.WaitCursor
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cancel.Click
BackgroundWorker1.CancelAsync()
End Sub
Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
go.Enabled = True
cancel.Enabled = False
Me.Cursor = Cursors.Arrow
DataGridView1.Refresh()
DataGridView1.CurrentCell = DataGridView1(0, DataGridView1.Rows.Count - 1)
End Sub
Dim f1 As String
Dim f2 As String
Dim ds As New DataSet
Dim command As MySqlCommand
Dim reader As MySqlDataReader
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
GetRecordCount()
Dim connetionString As String
Dim connection As MySqlConnection
Dim i As Integer = 0
Dim sql As String
connetionString = "Server=db4free.net;User Id=mouhcindinaoui;Password=$$$$$$;Database=mouhcindinaoui"
sql = "SELECT id,nom FROM dep02 "
connection = New MySqlConnection(connetionString)
Try
connection.Open()
command = New MySqlCommand(sql, connection)
reader = command.ExecuteReader()
For Value As Integer = 0 To rowcount
If reader.HasRows Then
Do While reader.Read()
f1 = reader.GetString("id")
f2 = reader.GetString("nom")
Loop
End If
ListText = String.Concat("Sequence #", Value)
BackgroundWorker1.ReportProgress(Value, ListText)
Thread.Sleep(10)
Next
reader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
' MsgBox("Can not open connection ! ")
End Try
End Sub
Private Sub GetRecordCount()
Dim connetionString As String
Dim connection As MySqlConnection
Dim command As MySqlCommand
Dim sql As String
connetionString = "Server=db4free.net;User Id=mouhcindinaoui;Password=dinaouimouhcin1991;Database=mouhcindinaoui"
sql = "Select count(*) from dep02"
connection = New MySqlConnection(connetionString)
command = New MySqlCommand(sql, connection)
connection.Open()
RowCount = CInt(command.ExecuteScalar())
End Sub
End Class
You are calling ReportProgress only at the end of the loop on the DataReader. Of course, at that point the two variables f1 and f2 used to set items in your grid contain the value of the last record read by the DataReader.
You need to move the call inside the DataReader loop
For Value As Integer = 0 To rowcount
If reader.HasRows Then
Do While reader.Read()
f1 = reader.GetString("id")
f2 = reader.GetString("nom")
ListText = String.Concat("Sequence #", Value)
BackgroundWorker1.ReportProgress(Value, ListText)
Loop
End If
Thread.Sleep(10)
Next
However it is totally useless the call to GetRecordCount and the external loop on the rowcount variable (and plain wrong). The while loop on the DataReader doesn't need it and your could remove all of it replacing everything with a simple increment of a local variable to keep the progressive of the current record inside the datareader loop
Dim recNum = 1
If reader.HasRows Then
Do While reader.Read()
f1 = reader.GetString("id")
f2 = reader.GetString("nom")
ListText = String.Concat("Sequence #", recNum)
BackgroundWorker1.ReportProgress(Value, ListText)
recNum = recNum + 1
Loop
End If
Can someone help me out. I have a combobox where the items are from my database. If I drop down the combobox and select an item, the datagridview must show the firstname,lastname etc. My data type at studentno is varchar, the int does not work too. The data will be get from two different table
2nd is how can I refresh the combobox? Because I need to close then reopen the program before the data that will be insert at combobox.
Private Sub ComboBox6_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox6.SelectedIndexChanged
conn.Open()
query = "select student.studentno,student.firstname,student.middlename,student.lastname,subject.subjcode,subject.subjdesc from student,subject where student.studentno = '" & ComboBox6.SelectedText & "' "
cmd = New MySqlCommand(query, conn)
da.SelectCommand = cmd
ds = New DataSet
da.Fill(ds, "ds_student,subject")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "ds_student,subject"
conn.Close()
End Sub
I had the same problem as you and then i came up with this
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Folha de Obra com Tabela Clientes.accdb;Persist Security Info=True")
Dim query As String
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
conn.Open()
query = ("select * from Obras where IdCliente = " & ComboBox1.ValueMember)
cmd = New OleDb.OleDbCommand(query, conn)
da.SelectCommand = cmd
da.Fill(ds, "NomeObra")
ComboBox2.DataSource = ds.Tables(0)
ComboBox2.DisplayMember = "NomeObra"
ComboBox2.ValueMember = "IdCliente"
conn.Close()
End Sub
I hope it helps you
I have a Datagridview and I want to delete a row in my MySQL database.
I have some code but I get an error, it says ID is null. My ID is a string which is the value of the ID where the columns are checked. My first column "column 0" is a checkbox column
Here is the code:
Feel free to ask specific questions if you don't understand what I am asking.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim RowsToDelete As New List(Of DataGridViewRow)
Try
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = True Then
DeleteRow(row.Cells(1).Value)
RowsToDelete.Add(row)
End If
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
For Each rowtodelete In RowsToDelete
DataGridView1.Rows.Remove(rowtodelete)
next
End Sub
Private Sub DeleteRow(ByVal ID As Integer)
Dim MySQLCon As New MySqlConnection
Dim ConnectionString As String = "server=localhost;user id=root;password=;database=business elements"
MySQLCon.ConnectionString = ConnectionString
Dim CMD As MySqlCommand
MySQLCon.Open()
Try
CMD.Connection = MySQLCon
CMD.CommandText = "DELETE FROM `users` WHERE `ID` = " & ID
Catch ex As Exception
End Try
MySQLCon.Close()
MySQLCon.Dispose()
End Sub
Without seeing all of your code, something like this should work:
Dim sql as String
sql = "DELETE FROM `users` WHERE `ID` IN ("
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = True Then
ID = row.Cells(1).Value
DeleteRow(row.Cells(1).Value)
RowsToDelete.Add(row)
sql += ID + ","
End If
Next
If sql.Left(sql.Length-1) = "," Then
CMD.CommandText = sql.Left(sql.Length-1) + ")"
CMD.Connection = MySQLCon
CMD.ExecuteNonQuery()
End If
Good luck.
Finally found the code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim RowsToDelete As New List(Of DataGridViewRow)
Try
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = True Then
DeleteRow(row.Cells(1).Value)
RowsToDelete.Add(row)
End If
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
For Each rowtodelete In RowsToDelete
DataGridView1.Rows.Remove(rowtodelete)
Next
End Sub
Private Sub DeleteRow(ByVal ID As Integer)
Dim MySQLCon As New MySqlConnection
Dim ConnectionString As String = "server=localhost;user id=root;password=;database=business elements"
MySQLCon.ConnectionString = ConnectionString
Dim CMD As New MySqlCommand
CMD.CommandText = "DELETE FROM `users` WHERE `ID` = " & ID
MySQLCon.Open()
Try
CMD.Connection = MySQLCon
CMD.ExecuteNonQuery()
Catch ex As Exception
End Try
MySQLCon.Close()
MySQLCon.Dispose()
End Sub
For i As Integer = DataGridView2.Rows.Count - 1 To 0 Step -1
Dim c As Boolean
c = DataGridView2.Rows(i).Cells(0).Value
If c = True Then
=====================================================================================
Dim sql As String = "DELETE FROM Items WHERE ItemID=" & Int(DataGridView2(1, DataGridView2.Rows(i).Index).Value)
' ^^^^^^^^^^^^^^
'
Dim comm As New SqlCommand(sql, con)
con.Open()
Dim result As Integer = comm.ExecuteNonQuery
con.Close()
End If
Next