Naeem Shah Naeem Shah - 2 months ago 7
C# Question

The connection was not closed the connection's current state is open

How to fix this problem; connection already closed in my function:

SqlConnection con=new SqlConnection(@"Here is My Connection");

public void run_runcommand(string query)
{

try
{
con.Open();
SqlCommand cmd1 = new SqlCommand(query, con);

cmd1.ExecuteNonQuery();
con.Close();
}
catch (Exception ex) { throw ex; }
}
//...
try
{
string query="my query";
db.run_runcommand(query);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

Answer

Better you write finally block and within it con.close() every where wherere you used try catch blocks. Eg.

    public void run_runcommand(string query)   
    {   
        try   
        {   
            con.Open();   
            SqlCommand cmd1 = new SqlCommand(query, con);   

            cmd1.ExecuteNonQuery();    
            con.Close();    
        }    
        catch (Exception ex)
        {
           throw ex; //TODO: Please log it or remove the catch
        }
        finally
        {
           con.close();
        }

    }    
try       
{           
string query="my query";           
db.run_runcommand(query);          
}         
catch(Exception ex)            
{         
MessageBox.Show(ex.Message);              
}   
finally
{
   con.close();
}

'