user6363145
user6363145

Reputation: 39

Delete a row through DataGridView

I have a Button that lists to me everything from a database and another Button that was made to delete something from database by "Name". To do that, I have a TextBox where I input the "Name" and delete it from the database.

To make things easy and faster I had another solution which is simpler than what I am currently doing. What I want it to do is click on a row and then press the delete Button and have the row be deleted from the database. I found this solution but this doesn't work:

For Each row As DataGridViewRow In myDataGrid.SelectedRows
    myDataGrid.Rows.Remove(row)
Next

Basically what I have to do in the code is make a query and select the row that I want right?

Upvotes: 0

Views: 239

Answers (2)

Bugs
Bugs

Reputation: 4489

The For[...]Next statement will only delete the DataGridViewRow from the DataGridView. It won't commit any changes to the database.

A DataGridView is a view of the data. You would need to commit the changes on the DataSet.

If you want a more specific answer post the code that shows how you are binding the data to the DataGridView.

Upvotes: 1

coder32
coder32

Reputation: 191

My apologies I am not able to comment. In either case, if you are trying to delete the record from the database, you will have to use a delete query.

Below is an example on how to do it:

delete selected row from datagridview and datasource table

Without using a stored procedure you can use this code:

Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim cnstring As String = "Your connection String"
Dim sqlstring As String = "Delete from yourTable where column= your record"
cn = New OleDbConnection(cnstring)
cmd = New OleDbCommand(sqlstring, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()

Upvotes: 1

Related Questions