Database 在vb中从listview中的数据库中删除记录
我有个问题。在listview的属性中,选中复选框=“True”。使用此复选框,我想删除listview和数据库中的数据 代码如下:Database 在vb中从listview中的数据库中删除记录,database,vb.net,listview,Database,Vb.net,Listview,我有个问题。在listview的属性中,选中复选框=“True”。使用此复选框,我想删除listview和数据库中的数据 代码如下: If MessageBox.Show("Do you really want to DELETE this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then MsgBox("Operation cancel", M
If MessageBox.Show("Do you really want to DELETE this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation cancel", MsgBoxStyle.Information, "Information")
End If
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = @code"
Using con = New SqlConnection(dbSource)
Using cmd = New SqlCommand(sql, con)
con.Open()
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
cmd.Parameters.AddWithValue("@code", ColumnRoomCode.Text)
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
使用上述代码,仅删除listview中的数据。数据库中的数据未被删除
listviewitem的界面:
如果你们都能帮助我,谢谢你们。:) 应执行命令以对数据库产生任何影响。你需要加上这个
cmd.ExecuteNonQuery()
在每个循环中
此外,连接可以在进入环路之前打开,然后应该关闭。(此处建议使用语句)
话虽如此,请看一看参数化查询,因为您的代码容易出现Sql注入和解析问题。此外,用于删除记录的sql命令不需要在FROM表部分之后列出字段列表
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
' Parameterized query
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = @code"
' Using statement to ensure proper closing and disposing
' of the objects SqlConnection and SqlCommand
using con = New SqlConnection(dbSource)
using cmd = New SqlCommand(sql, con)
con.Open()
' Add a parameter just one time before the loop with an empty string
cmd.Parameters.AddWithValue("@code", "")
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
' Set the parameter value with the value extracted from the ListViewItem
Dim RoomCode = lvItem.Text
cmd.Parameters("@code").Value = RoomCode
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
End Sub
最后一个音符。ColumnRoomCode文本框(?)始终是相同的,因此调用delete一次就足够了,但我认为应该使用当前ListViewItem所附加的一些值来更改此设置。ColumnRoomCode是列在listview中有一个复选框,而不是文本框。我尝试上面的代码。但结果仍然是一样的。重新加载应用程序后,先前删除的数据不会在数据库中删除。tqSo,删除where子句中要传递的房间代码在哪里?。您需要它才能删除选中的行。对不起,我不明白您删除单个记录(对应于选中项的记录)的意思。您需要指示数据库如何在表室中查找该记录。这是需要为参数@code传递的值。它应该是唯一标识表中记录的值(我假设ColumnRoomCode就是该值。如果不是,那么如何标识要删除的记录?)是的,ColumnRoomCode是指示数据库在表中查找记录的值。