i have a remove button like i would like to delete just sigle selected row from both datagridview and the acutual database.the problem I am having is in deleting selected row.if i dont use the parameter the contents of the table gets deleted ,i dont have any primery key just an ID field (AutoNumber).can someone help me with a sql statement please
i appreciate your help
enter code here
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
If Not DataGridView1.CurrentRow.IsNewRow Then
If DataGridView1.SelectedRows.Count = 0 Then
MsgBox("No row was selected. If you are trying to remove a row, highlight the entire row by clicking on the identifier column on the far left.", MessageBoxIcon.Error, "Entire Row Not Selected")
ElseIf DataGridView1.SelectedRows.Count = 1 Then
Dim response As DialogResult = MessageBox.Show("Are you sure you want to delete the selected row?", "Delete row?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If (response = DialogResult.Yes) Then
DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim cnstring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\testdb1.accdb;Persist Security Info=False")
Dim sqlstring As String = "Delete from sample where id = id"
cn = New OleDbConnection(cnstring)
cmd = New Ol开发者_如何学JAVAeDbCommand(sqlstring, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End If
ElseIf DataGridView1.SelectedRows.Count > 1 Then
MsgBox("Multiple rows are currently selected. The remove function can only delete one row at a time. Please select a single row and try again.", MessageBoxIcon.Error, "Single Row Not Selected")
DataGridView1.ClearSelection()
End If
End If
End Sub
End Class
enter code here
While you are populating the data from the DB to datagridview, you can include the ID
field too, but while showing data you can hide it. Then when you want to delete data you will have the ID
in order to do that.
For example, suppose that we have as below:
sqlcommand command = new sqlcommand("SELECT IDHuman,HumanName,... FROM tblHuman",connection)
Now as you see, we have the ID as well and we should hide it as follows:
datagridview1.cells[0].visible=false;
Then when you want to delete it, you can include ID
in your WHERE
clause.
精彩评论