从datagridview和datasource表中删除所选行

时间:2011-02-22 04:22:50

标签: asp.net vb.net

我有一个删除按钮,就像我想从datagridview和acutual数据库中删除只有sigle选择的行。我遇到的问题是删除选定的row.if我不使用该参数表的内容被删除,我没有任何质量键只是一个ID字段(自动编号)。有人帮我提供一个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

1 个答案:

答案 0 :(得分:1)

当您将数据从数据库填充到datagridview时,您也可以包含ID字段,但在显示数据时您可以隐藏它。然后,当您要删除数据时,您将拥有ID以便执行此操作。

例如,假设我们具有以下内容:

sqlcommand command = new sqlcommand("SELECT IDHuman,HumanName,... FROM tblHuman",connection)

现在如您所见,我们也有ID,我们应该按如下方式隐藏它:

datagridview1.cells[0].visible=false;

然后,当您要删除它时,可以在ID子句中加入WHERE