我正在 Visual Basic 2010 中制作发票系统,但我被困在这里
这是我的代码
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
For Each row As DataGridViewRow In datagrid.SelectedRows
Dim selectedindex As String = datagrid.CurrentRow.Cells(0).Value.ToString()
datagrid.Rows.Remove(row)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sql = "DELETE FROM sales WHERE InvoiceNo='" & txtInvoiceNo.Text & "' and id='" & selectedindex & "'"
Dim cmd As New MySqlCommand(sql, conn)
Dim reader As MySqlDataReader = cmd.ExecuteReader
If reader.Read() Then
End If
conn.Close()
reader.Close()
Next
End Sub
此代码无法正常工作,请查看我的发票屏幕截图并建议我更好的代码
当我尝试删除选定的行时,代码不起作用,如果有人可以告诉我我可以删除多个选定的行吗?它们从数据网格中删除,但不从数据库中删除
最佳答案
试试这个:
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Using cn As New MySqlConnection("Connection string here"), _
cmd As New MySqlCommand("DELETE sales WHERE InvoiceNo= ?InvoiceNo and id= ?id", cn)
cmd.Parameters.Add("?InvoiceNo", MySqlDbTypes.VarChar, 10).Value = txtInvoiceNo.Text
cmd.Parameters.Add("?id", MySqlDbTypes.Int32)
cn.Open()
For Each row As DataGridViewRow In datagrid.SelectedRows
cmd.Parameters(1).Value = row.Cells(0).Value
cmd.ExecuteNonQuery()
datagrid.Rows.Remove(row)
Next row
End Using
End Sub
看起来您正在尝试保存并重新使用单个连接对象,然后根据需要打开它。这是错误的:它破坏了 .Net 进行连接池的能力。您确实希望为与数据库对话的每个位置创建一个新的连接对象。这还可以让您更好地确保在错误查询后正确关闭连接。最后,使用查询参数将保护您的应用免受 SQL 注入(inject)攻击。
关于mysql - Visual Basic MySQL Datagrid 从数据库中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9632808/