You're sharing the same connection object across multiple methods, which is a bad idea.
When you call the
getDetails
method, the shared connection object is
already open, so the
con.Open
call throws an exception. The
Finally
block then closes the connection, so your
ExecuteNonQuery
call fails as well.
The best solution would be to update your
mark_attendance
stored procedure to read the name and department for the passed-in employee ID.
Otherwise, you'll need to execute two queries for each checked item:
Private Sub btnmark_Click(sender As Object, e As EventArgs) Handles btnmark.Click
Using connection As New SqlConnection("YOUR CONNECTION STRING HERE")
Using markCommand As New SqlCommand("mark_attendance", connection)
Using getDetailsCommand As New SqlCommand("SELECT empname,dept from emp_master where empid = @empid", connection)
markCommand.CommandType = CommandType.StoredProcedure
connection.Open()
For Each employee In CheckedListBox1.CheckedItems
Dim empid As String = CheckedListBox1.GetItemText(employee)
Dim empname, dept As String
getDetailsCommand.Parameters.Clear()
getDetailsCommand.Parameters.AddWithValue("@empid", empid)
Using dr As SqlDataReader = getDetailsCommand.ExecuteReader()
If dr.Read() Then
empname = CStr(dr("empname"))
dept = CStr(dr("dept"))
End If
End Using
markCommand.Parameters.Clear()
markCommand.Parameters.AddWithValue("@empid", empid)
markCommand.Parameters.AddWithValue("@empname", empname)
markCommand.Parameters.AddWithValue("@dept", dept)
markCommand.Parameters.AddWithValue("@date", DateTime.Today)
markCommand.ExecuteNonQuery()
Next
MsgBox("Attendance Marked...!", MsgBoxStyle.Information)
End Using
End Using
End Using
End Sub