Search code examples
c#sqlconnection

I can open SqlConnection once, but I can't do it again


My program runs, and it initially connects to the database successfully. I can run queries and everything works fine. However, I cant seem to disconnect and reconnect to the database. The output says: "A first chance exception of type 'System.InvalidOperationException' occurred in System.Data.dll" Here is my connection method:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    class TCNInteraction
    {
        static string connectionString = "Server=localhost\\SQLEXPRESS;Database=TCN;Trusted_Connection=true";
        Button theButton;
        TextBox theTextBox;
        bool currentlyConnectedToADatabase = false;
        SqlConnection cnn = new SqlConnection(connectionString);
        /*
         *Uses the already existing SQL connection string and attempts to establish a connection 
         */
        public bool connectToDatabase(Button inputButton, TextBox inputDatabaseBox)
        {
            theButton = inputButton;
            try
            {
                Console.WriteLine("Attempting to open connection...");
                if (cnn.State != ConnectionState.Open)
                {
                    Console.WriteLine("About to open the connection");
                    cnn.Open();
                }
                Console.Write("I opened the connection!");
                currentlyConnectedToADatabase = true;
                displayRowsOfDatabase(inputDatabaseBox);
                theButton.Text = "Connected";
                return true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot open connection!");
                return false;
            }
            finally
            {
                cnn.Close();
            }

        }

        private void displayRowsOfDatabase(TextBox inputDatabaseBox)
        {

            theTextBox = inputDatabaseBox;
            using (cnn)
            {

                SqlCommand command = new SqlCommand("SELECT SomeNumber,SomeText, AnotherNumber FROM tcn.Demo;", cnn);
                SqlDataReader reader = command.ExecuteReader();


                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string printString = int.Parse(reader["SomeNumber"].ToString()) + " " + reader["SomeText"].ToString() + " " + int.Parse(reader["AnotherNumber"].ToString()) + Environment.NewLine;
                        theTextBox.Text += printString;
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
                reader.Close();
            }
            cnn.Close();
        }


        public void disconnectFromDatabase()
        {
            MessageBox.Show("Disconnected from Database");
            cnn.Close();
            theButton.Text = "Connect to Database";
            //theTextBox.Text = "";
            currentlyConnectedToADatabase = false;
        }
    }
}

Solution

  • Your try/catch block is not closing your connection. Give the responsibility to close the connection to the finally block. It will close the connection even if any exception occurs in the program. Try as following...

    public bool connectToDatabase(Button inputButton, TextBox inputDatabaseBox)
    {
        theButton = inputButton;
        try
        {
                Console.WriteLine("Attempting to open connection...");
    
                //THIS IS WHERE I GET STUCK THE SECOND TIME
                if (cnn.State != ConnectionState.Open)
                {
                    cnn.Open();
                }
                Console.Write("I opened the connection!");
                currentlyConnectedToADatabase = true;
                displayRowsOfDatabase(inputDatabaseBox);
                theButton.Text = "Connected";
                return true;
    
        }
        catch (Exception ex)
        {
            MessageBox.Show("Cannot open connection!");
        }
        finally
        {
            cnn.Close();
        }
    
    }
    public void disconnectFromDatabase()
        {
            MessageBox.Show("Disconnected from Database");
            if(cnn.State == ConnectionState.Open)
            {
                cnn.Close();
            }
            theButton.Text = "Connect to Database";
            //theTextBox.Text = "";
            currentlyConnectedToADatabase = false;
        }