Skip to content
Advertisement

‘ExecuteNonQuery requires an open and available Connection. The connection’s current state is closed.’ – C#

The code:

This error shows up when I click the save button:

System.InvalidOperationException: ‘ExecuteNonQuery requires an open and available Connection. The connection’s current state is closed.’

I am using the using keyword, if I’m correct doesn’t using automatically opens and closes the sqlConnection? If so, why does it returns an error that I need an open and available connection for the ExecuteNonQuery()? How can I fix this? Should I just simply add the Open and Close syntax? or is there a better way to do this

The LoadData() method:

Advertisement

Answer

You can simply use con.Open() so connection will just get establish in case of closed state or you can add a check before opening connection (snippet below).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement