简体   繁体   中英

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. I have an update button that pushes the edited data back to the 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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