We help IT Professionals succeed at work.
Get Started

C# executing a command after opening connection to SQL database

rwheeler23 asked
Last Modified: 2017-11-19
I have this method that gets the connection string. I first have a method that builds the connection string. Then I open the connection and finally I try to execute a SQL stored procedure against this connection. As soon as I try to execute the sp I get the message "Connection property has not been initialized" What am I missing and how do I correct this?

        public static SqlConnection GetConnection(string ConnectionString)
            /* Create and open a connection to the SQL Server */
            /* Return open connection object */
            SqlConnection SQLConn = new SqlConnection();

            string loginType = Properties.Settings.Default.SQLLogintype.ToUpper();

                if (loginType == "WINDOWS")
                    SQLConn.ConnectionString = ConnectionStringWindows(ConnectionString);
                if(loginType == "SQL")
                    SQLConn.ConnectionString = ConnectionStringSQL(ConnectionString);

                return SQLConn;
            catch (Exception ex)
                Log.Write("Failed to get SQL connection to the database " + Controller.Instance.Model.SQLDatabase + ": " + ex.Message);
                throw ex;

/* Build the connection string */
        public static string ConnectionStringSQL(string ConnectionString)
            /* Return connection string for ".Net Framework Data Provider for SQL Server" (System.Data.SqlClient.SqlConnection) */
            return @"Data Source=" + Properties.Settings.Default.SQLSERVER + ";Initial Catalog=" + Properties.Settings.Default.SQLDatabase + ";User Id=" + Properties.Settings.Default.SQLUserID + ";Password=" + Properties.Settings.Default.SQLPassword + ";" + Properties.Settings.Default.SQLOption;
            /* Open the connection */
            SqlConnection DataConnection = DataAccess.GetConnection(ConnectionString);
Execute stored procedure to insert record
            cmd.Connection = DataConnection;
Watch Question
This problem has been solved!
Unlock 2 Answers and 17 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE