Update database from datagridview in VB.NET. i have a datagridview in my form. Data read from database to datagridview is working properly. But i cant update the cahanges. I use this code for update the database.
The problem is there is no changes in Database. I am using SQL database.
Code:
Private Sub BTNUPDATE_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTNUPDATE.Click
DTPEDITAT.Value = Format(DTPEDITAT.Value, "dd/MM/yyyy")
Dim query As SqlCommand
getConnect()
Try
Conn.Open()
Dim id As Integer
Dim status As Double
Dim name As String
Dim ateditdate As String
Dim remark As String
ateditdate = DTPEDITAT.Value.ToString()
For x As Integer = 0 To Me.ATCEDITGRID.Rows.Count - 1
id = 0
status = 2
name = ""
remark = ""
id = Me.ATCEDITGRID.Rows(x).Cells(0).Value
name = Me.ATCEDITGRID.Rows(x).Cells(1).Value
If Me.ATCEDITGRID.Rows(x).Cells(2).EditedFormattedValue = "Present" Then
status = 1
ElseIf Me.ATCEDITGRID.Rows(x).Cells(2).EditedFormattedValue = "Halfday" Then
status = 0.5
ElseIf Me.ATCEDITGRID.Rows(x).Cells(2).EditedFormattedValue = "Absent" Then
status = 0
Else
status = 2
End If
If Me.ATCEDITGRID.Rows(x).Cells(3).EditedFormattedValue = "" Then
remark = ""
Else
remark = Me.ATCEDITGRID.Rows(x).Cells(3).EditedFormattedValue
End If
Dim strSQL As String = "UPDATE ATTENDANCE SET [EMP_ID]=@EMP_ID,[EMP_NAME]=@EMP_NAME,[AT_STATUS]=@AT_STATUS,[AT_REMARK]=@AT_REMARK WHERE AT_DATE='" & ateditdate & "'"
query = New SqlCommand(strSQL, Conn)
query.Parameters.AddWithValue("@EMP_ID", id)
query.Parameters.AddWithValue("@EMP_NAME", name)
query.Parameters.AddWithValue("@AT_STATUS", status)
query.Parameters.AddWithValue("@AT_REMARK", remark)
query.ExecuteNonQuery()
Next x
Conn.Close()
MessageBox.Show("Updated Successfully!", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information)
BTNCLEAR.PerformClick()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub