我有一个删除按钮,准备好从Datagridview
中选择一行后再按下按钮,它将从数据库中删除该列。但我刚刚意识到问题已经出现,我无法修复它。问题很简单,按下按钮后它应删除并更新Datagridview
而不删除内容,但这不会发生。这就是事情,这是删除按钮的代码
Private Sub cmdDelete_Click(sender As Object, e As EventArgs) Handles cmdDelete.Click
SQLCon = New SqlConnection
SQLCon.ConnectionString = "...."
rbPorData.Checked = False
rbPorExtensão.Checked = False
rbPorNome.Checked = False
Try
SQLCon.Open()
If MsgBox("Tem a certeza que deseja eliminar " & apagarTextBox.Text & "?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
For i As Integer = Me.DataGridView2.SelectedRows.Count - 1 To 0 Step -1
cmdDelete = "DELETE infofile WHERE Filename='" & Me.DataGridView2.SelectedRows(i).Cells(0).Value.ToString() & "'"
SQLDA = New SqlDataAdapter(cmdDelete, SQLCon)
SQLDataSet = New DataSet()
SQLDA.Fill(SQLDataSet)
Me.DataGridView2.Rows.Remove(Me.DataGridView2.SelectedRows(i))
MessageBox.Show("Ficheiro apagado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
Next
SQLCon.Close()
UpdateDeletedFiles()
UpdateComboBoxDelete()
MostrarResultadoTotal()
ChangeLabelColor()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
SQLCon.Dispose()
End Try
End Sub
我做了一些测试。它的作用是在我单击该行并按下删除按钮后,它将刷新但不会删除datagridview和数据库。如果我再次尝试相同的过程,它将删除。我不知道为什么会发生这种情况
答案 0 :(得分:0)
将您的代码更改为:
cmdDelete = "DELETE from infofile WHERE Filename=@Filename"
cmd = New SqlCommand(cmdDelete , SQLCon)
cmd.Parameters.Add(New SqlParameter("@Filename", Me.DataGridView2.SelectedRows(i).Cells(0).Value.ToString() ))
nbre = cmd.ExecuteNonQuery()
答案 1 :(得分:0)
在dataadapter中提供SQL命令时,它是 select 命令(请参阅SqlDataAdapter Constructor (String, SqlConnection))。这可能不是你想要的。
您需要做的就是使用普通的SQL命令删除文件名,如下所示:
If MsgBox("Tem a certeza que deseja eliminar " & apagarTextBox.Text & "?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Try
Using sqlConn As New SqlConnection("...")
Dim sql = "DELETE FROM infofile WHERE Filename = @Filename"
Using sqlCmd As New SqlCommand(sql, sqlConn)
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@Filename", .SqlDbType = SqlDbType.NVarChar})
sqlConn.Open()
For i As Integer = Me.DataGridView2.SelectedRows.Count - 1 To 0 Step -1
Dim fn = Me.DataGridView2.SelectedRows(i).Cells(0).Value.ToString()
sqlCmd.Parameters("@Filename").Value = fn
sqlCmd.ExecuteNonQuery()
Next
For i As Integer = Me.DataGridView2.SelectedRows.Count - 1 To 0 Step -1
Me.DataGridView2.Rows.Remove(Me.DataGridView2.SelectedRows(i))
Next
sqlConn.Close()
End Using
End Using
MessageBox.Show("Ficheiro apagado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
UpdateDeletedFiles()
UpdateComboBoxDelete()
MostrarResultadoTotal()
ChangeLabelColor()
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End If