问题描述
我有一个删除按钮,就像我想从datagridview和aualual数据库中只删除选定的行一样.我遇到的问题是在删除选定的行中.如果我不使用该参数,则表的内容将被删除,我没有任何入门密钥,只是一个ID字段(AutoNumber).有人可以通过sql语句帮助我吗
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
感谢您的帮助
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
以便执行此操作.
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)
现在,如您所见,我们也有ID,我们应该按以下方式隐藏它:
Now as you see, we have the ID as well and we should hide it as follows:
datagridview1.cells[0].visible=false;
然后,当您要删除它时,可以在 WHERE
子句中包含 ID
.
Then when you want to delete it, you can include ID
in your WHERE
clause.
这篇关于从datagridview和datasource表中删除选定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!