我在datagridview中删除时出错
'If I change the code as below then successfully delete in DataGridView and database
'If I don't hide the "ID" column
'DataGridView1.Columns(0).Visible = False
'index column id appears that is starting at (0)
Dim iRow As Long = DataGridView1.Item(0,DataGridView1.CurrentRow.Index).Value
'In the SQL query where clause becomes id
Dim query = " DELETE FROM tblemployee WHERE ID = " & iRow
我想隐藏
Id
列(自动编号),我想用 EMPID
的 where 子句删除它。这个 EMPID
列被定义为数据类型 text
并且它是主键。也许我的代码有问题。
Public Sub Load_Data()
Try
Dim dt As New DataTable()
Dim query = "Select * From tblemployee"
Using adapter As New OleDbDataAdapter(query, Con)
adapter.Fill(dt)
End Using
Me.DataGridView1.DataSource = dt
DataGridView1.Columns(0).Visible = False
Catch ex As OleDbException
MessageBox.Show(ex.Message.ToString(), "ERROR Loading")
Finally
Con.Close()
End Try
End Sub
Private Sub DoSQL(ByVal Sql As String)
Cmd = New OleDb.OleDbCommand
If Con.State = ConnectionState.Closed Then Con.Open()
Try
Cmd.Connection = Con
Cmd.CommandType = CommandType.Text
Cmd.CommandText = Sql
Cmd.ExecuteNonQuery()
MessageBox.Show("Records Updated Completed.", "Update Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
Cmd.Dispose()
Catch ex As Exception
MsgBox("Error Update: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If DataGridView1.RowCount = 0 Then Exit Sub
Dim iRow As String = DataGridView1.Item(1, DataGridView1.CurrentRow.Index).Value
Dim FName As String = DataGridView1.Item(2, DataGridView1.CurrentRow.Index).Value
Dim Result As Byte = MessageBox.Show("Are you sure you want to delete the data?" & vbCrLf & "Full Name: " & FName, "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If Result = DialogResult.Yes Then
Dim query = " DELETE FROM tblemployee WHERE EMPID = " & iRow
DoSQL(query)
DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
Call Load_Data()
End If
End Sub
文本值应该用
' '
单引号括起来。
因此:
"DELETE FROM tblemployee WHERE EMPID = '" & iRow & "'"