如何从具有唯一ID的数据网格视图中删除记录而不删除具有相同唯一ID的其他记录?

时间:2017-01-18 02:15:58

标签: sql-server vb.net datagridview

Time-in_Time-out GUI。

enter image description here

我有我的Time-in Time-out窗口的这张图片。如您所见,我想在数据网格视图中删除某个员工的记录。我有这个代码。

conn = New SqlConnection(connStr)

conn.Open()

Try
    Dim cmd As New SqlCommand()
    cmd.Connection = conn

    cmd.CommandText = "DELETE FROM timelogTB WHERE EmpNo='" & Me.dgvTimelog.CurrentRow.Cells(1).Value & "'"

    Dim rowsAffected As Integer = cmd.ExecuteNonQuery()

    If rowsAffected > 0 Then
        MsgBox("Record has been deleted!", MsgBoxStyle.Information, "Successful")
    Else
        MsgBox("Failed to delete records!", MsgBoxStyle.Exclamation, "Deleting Failed...")
    End If

        cmd.Dispose()

Me.dgvTimelog.Rows.Remove(Me.dgvTimelog.CurrentRow)
conn.Close()

Catch ex As Exception
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

问题在于,当我单击特定日期的1条记录时,该员工的所有记录也会从之前的日期删除。我试过把where子句但没有任何反应。而且如果用户真的想要删除记录,我想要一个条件语句,我有这个代码。

If MsgBox("Do you really want to delete this record?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, "Deleting...") = MsgBoxResult.Yes Then 
MsgBox("Record deleted permanently!", MsgBoxStyle.Information, "Delete!")

但即使用户选择否,仍会删除记录。谁能告诉我什么似乎是问题。提前谢谢!

这个问题已经完成,试试这段代码就可以了: Private Sub btnDelete_Click_1(ByVal sender As System.Object,ByVal e As System.EventArgs)处理btnDelete.Click         尝试             如果MsgBox("你真的想要删除这条记录吗?",MsgBoxStyle.YesNo或MsgBoxStyle.Exclamation,"删除记录......")= MsgBoxResult.Yes然后                 deleteRecords()             其他                 MsgBox("记录未删除!",MsgBoxStyle.Information,"删除记录......")             万一         赶上前例外             MessageBox.Show(ex.Message,"错误",MessageBoxButtons.OK,MessageBoxIcon.Error)         结束尝试     结束子     Sub deleteRecords()         conn = New SqlConnection(connStr)

    conn.Open()

    Try
        Dim cmd As New SqlCommand()
        cmd.Connection = conn

        cmd.CommandText = "DELETE FROM timelogTB WHERE LogID=@LogID"

        cmd.Parameters.Add(New SqlParameter("@LogID", SqlDbType.Int, 11, "LogID"))
        cmd.Parameters("@LogID").Value = dgvTimelog.CurrentRow.Cells(0).Value

        Dim rowsAffected As Integer = cmd.ExecuteNonQuery()

        If rowsAffected > 0 Then

            MsgBox("Record deleted permanently!", MsgBoxStyle.Information, "Delete!")

        End If

        cmd.Dispose()

        Me.dgvTimelog.Rows.Remove(Me.dgvTimelog.CurrentRow)

        conn.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

谢谢大家!

0 个答案:

没有答案