Click here to Skip to main content
15,845,213 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My vb.net application shows an error.

"Connection not closed. Connection's current state is open"
Here is my code. Please help me rectify the error:

VB
Private Sub saveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles          saveBtn.Click
        addSubject()
       End Sub

    Private Function addSubject() As Boolean
      Dim cmd As New SqlCommand
      Dim ok As Boolean = False
      cmd.Connection = con
      cmd.CommandText = " INSERT INTO Subjects(subject_name) VALUES(@inn)"
      cmd.CommandType = CommandType.Text
      cmd.Parameters.AddWithValue("inn", subjectTxt.Text)

      Try
        con.Open()
        cmd.ExecuteNonQuery()
        ok = True

      Catch ex As Exception
          MessageBox.Show(ex.Message, "Add failed")
         ok = False
       End Try
      cmd.Dispose()
      con.Close()
      Return ok

      con.Close()
    End Function
Posted

declare connection as Public ,then First close connection if anything is open Then Open it
 
Share this answer
 
Hi u r try to open connection,but that connection is already opened,it not in close state,so remove con.open and try

Remove any one con.Close() form catch block.

Where u declare con ? did u declare con as public variable ?
 
Share this answer
 
v4
Comments
hlsc1983 12-Mar-14 1:12am    
i removed con and now its showing another error.
" there's already an open datareader associated with this connection which must be close first!"

con is declared in a module
Aravindba 12-Mar-14 1:21am    
ok u check each function ,in any one function con is not closed,then u try to open con in above mention function ,so fully u check ur code and close con in every function ,use try...catch...finally, in finally block u need to dispose first any datareader or datable or dataset or cmd and then try to close con.

Try
con.Open()
cmd.ExecuteNonQuery()
ok = True
con.Close()// Add here close con
Catch ex As Exception
MessageBox.Show(ex.Message, "Add failed")
ok = False
End Try
cmd.Dispose()
con.Close()
Return ok

con.Close()//Remove this
End Function

Try to use finally in try catch,so only if success or any error it goes to finally block and u can dispose and close

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900