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);
}
}
usingkeyword disposes of the object in question once it has left the using block, so your connection only exists untilInfoTableConnection.Open();is called, and then it is disposed ofusingbut then you will have to callInfoTableConnection.Dispose()when you're done