简体   繁体   English

如何使用DataGridView和按钮删除DataGridView中的SQL条目

[英]How to use DataGridView and a button to delete a SQL entry in my DataGridView

So I've got my SQL connection setup and working and it pulls and binds the data to the datagridview. 因此,我已经建立了SQL连接并可以正常工作,它可以将数据拉取并绑定到datagridview。 I have an update button that pushes the edited data back to the SQL server. 我有一个更新按钮,可将已编辑的数据推回到SQL Server。

Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
    'Delete Current Cell Data 
    Dim deleteCmd As String = "Delete FROM Contacts WHERE au_id = @Id;"
    Dim myCommand As SqlCommand = New SqlCommand(deleteCmd)
    myCommand.Parameters.Add(New SqlParameter("@Id", SqlDbType.VarChar, 11))

    'Start the SqlCommand "@Id" parameter to the ID of the row that was clicked.
    myCommand.Parameters("@Id").Value = DataGridView1.SelectedCells

Now I am currently working on getting a delete button to function. 现在,我目前正在努力使删除按钮起作用。 Basically I need it to Delete the row of data that is currently selected. 基本上,我需要它来删除当前选定的数据行。

Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click If DataGridView1.SelectedRows.Count > 0 Then 'you may want to add a confirmation message, and if the user confirms delete DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0)) Else MessageBox.Show("Select 1 row before you hit Delete") End If End Sub

This is what I came up with! 这就是我想出的! I was going about it all wrong attempting to do it via SQL queries. 我试图通过SQL查询来做这一切都是错误的。 Just needed to do it locally and then use my update button to finish the changes. 只需在本地执行,然后使用我的更新按钮即可完成更改。 Which will probably be safer given that end users are end users. 鉴于最终用户是最终用户,这可能会更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM