2014-05-23 64 views
-1

我有一个问题。在listview属性中是checkboxes =“True”。使用这个复选框,我想删除列表视图和数据库中的数据。从列表视图中的数据库删除记录在vb

下面是代码:

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 

使用上述代码中,仅在列表视图中的数据被删除。数据库中的数据未被删除。

的ListViewItem的接口:

enter image description here

谢谢你,如果你都可以帮助我。 :)

回答

2

应执行命令以对数据库有任何影响。您需要在每个循环中添加此

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提供

+0

ColumnRoomCode是列中有一个复选框,而不是文本框。我尝试上面的代码。但结果仍然相同。重新加载应用程序后,先前的数据删除不会删除数据库中.tq – siyhaz

+0

那么,您在哪里将RoomCode传递给DELETE WHERE子句?您需要它才能删除选中的行。 – Steve

+0

对不起,但我不明白你的意思 – siyhaz