![](/img/trans.png)
[英]How to delete row from gridview with List<> Datasource using OnRowDeleting
[英]delete selected row from datagridview and datasource table
我有一個刪除按鈕,就像我想從datagridview和acutual database中刪除單行一樣。我遇到的問題是在刪除所選行中。如果我不使用該參數,則表的內容將被刪除,我不有任何入門密鑰只是一個ID字段(AutoNumber)。有人可以通過sql語句幫助我嗎
我感謝您的幫助
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 OleDbCommand(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
在將數據從數據庫填充到datagridview時,也可以包括ID
字段,但是在顯示數據時可以將其隱藏。 然后,當您要刪除數據時,您將具有ID
以執行此操作。
例如,假設我們具有以下內容:
sqlcommand command = new sqlcommand("SELECT IDHuman,HumanName,... FROM tblHuman",connection)
現在,正如您所看到的,我們也有該ID,並且應按以下所示隱藏它:
datagridview1.cells[0].visible=false;
然后,當您要刪除它時,可以在WHERE
子句中包含ID
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.