i have an application. which is executed after every 5 mins. i have an open connection but it gives me the following error:

ExecuteScalar requires an open and available Connection. The connection's current state is closed.

my code is something like this. I have shown where all i am using ExceuteScalar()

Sub Main()

try

   connection.open()

       cmd.ExecuteScalar()   

    Check1()

   Check2()

Catch()

      cmd.ExecuteScalar()   

  Finally

      cmd.ExecuteScalar()   <---- gives an error

      connection.close()

End Sub

public Sub check1()

dim str1 as String ="Select query"

Dim cmd1 As SqlCommand = New SqlCommand(str1, connection)

Dim rdr As SqlDataReader = cmd1.ExecuteReader()

While rdr.Read()

list1.Add(rdr.Item(0))

End While

rdr.Close()

End Sub

public Sub check2()

dim str2 as String ="Select query"

Dim cmd2 As SqlCommand = New SqlCommand(str2, connection)

Dim rdr As SqlDataReader = cmd2.ExecuteReader()

While rdr.Read()

list1.Add(rdr.Item(0))

End While

rdr.Close()

End Sub

how can solve this problem?

You probably have an error already while connection to your datasource. The Finally block get executed, no matter what. means if there is an error on the connection, then the execute command will fail as well. try to use this code and see what error message pops up:

Try

			connection.open()
			cmd.ExecuteScalar()
			Check1()
			Check2()

		Catch(ex as Exception)

			MsgBox(ex.ToString)

		Finally

			connection.close()
		End Try
This article has been dead for over six months. Start a new discussion instead.