0

So I noticed in my code I had a lot of repetitive connection strings and decided to clean it up a little bit.

My issue is, now that I've put the connection string into a seperate class I can no longer open the connection when using using (InfoTableConnection = new SqlConnection(infoTableConnString))

However if I don't use using it works fine.

I'm not quite understanding how it works I guess. Here is my code if someone could explain what exactly is happening once it's introduced to a class and/or how to fix it.

Connection Class: Connection.cs

class Connection
    {
        public static SqlConnection InfoTableConnection = null;
        public void InfoConnection()
        {
            string infoTableConnString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MTRInfoTables;Integrated Security=True";

            using (InfoTableConnection = new SqlConnection(infoTableConnString))

            InfoTableConnection.Open();

        }
    }

Sample Code from: MainForm.cs

private void zGradeCombo()
        {
            try
            {

                //Connection string from class.
                Connection connInfoTable = new Connection();
                connInfoTable.InfoConnection();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = Connection.InfoTableConnection;
                cmd.CommandText = "SELECT * FROM [dbo].[Item] ORDER by [Type] ASC";

                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    cmbType.Items.Add(reader["Type"].ToString());
                }

                //Close connection from "Connection" class
                Connection.InfoTableConnection.Close();
            }

            //Catch Exception
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
3
  • 1
    The using keyword disposes of the object in question once it has left the using block, so your connection only exists until InfoTableConnection.Open(); is called, and then it is disposed of Commented Jan 23, 2017 at 15:32
  • So since it disposes the connection after it opens there's no way to use it in a class and call it from a separate form? Commented Jan 23, 2017 at 15:36
  • It can if you don't use using but then you will have to call InfoTableConnection.Dispose() when you're done Commented Jan 23, 2017 at 15:37

2 Answers 2

5

The using keyword makes sure that your object will be disposed when you reached the end of the scope so that all the resources will be cleaned up afterwards

using (InfoTableConnection = new SqlConnection(infoTableConnString))
{
        InfoTableConnection.Open();
} // <- At this point InfoTableConnection will be disposed (and closed) 

Since you care about disposing in the code around you do not need the using block in the constructor of the class. But it would be a good idea to implement IDisposable on your Connection class and use it like this:

using(var con = new Connection())
{
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con.InfoTableConnection;
    cmd.CommandText = "SELECT * FROM [dbo].[Item] ORDER by [Type] ASC";

    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        cmbType.Items.Add(reader["Type"].ToString());
    }
}

In the Dispose() method of your connection you should dispose the SQL Connection.

Sign up to request clarification or add additional context in comments.

Comments

1

If your goal is to have your connection string is one location, why not just place your connection string in your app.config (settings) file and reference it in the code from there?

app.config

<connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MTRInfoTables;Integrated Security=True" />
</connectionStrings>

code.cs

string myConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

You must include a reference to the System.Configuration.dll in your references to use ConfigurationManager.

This way, you can continue using your using statements they way that they were designed to be used.

1 Comment

Thanks... This makes it a lot cleaner too :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.