Most efficient way to test SQL connection string availibility

Marek picture Marek · Jul 25, 2013 · Viewed 52.7k times · Source

I have this code down which I tried to make it Test SQL string connectivity, but I dont know how to handle the part with connection.Open = true would you please help me to solve this out? Thank you so much for your time.

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection("Data Source='" + textBox1.Text + "';Initial Catalog='" + textBox2.Text + "';User ID='" + textBox3.Text + "';Password='" + textBox4.Text + "'"))
            {
                try
                {
                    connection.Open();
                    if (connection.Open == true) // if connection.Open was successful
                    {
                        MessageBox.Show("You have been successfully connected to the database!");
                    }
                    else
                    {
                        MessageBox.Show("Connection failed.");
                    }
                }
                catch (SqlException) { }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Chyba v přihlášení: " + ex);
        }
        finally
        {

        }
    }

It says: "Cannot asign 'open' because it is a 'methoud group' " I know that this code might be totaly bad, but I need to handle this somehow and have no idea what is the right way. Thank you.

This is what is not actually working for not-opened connection:

using (SqlConnection connection = new SqlConnection("Data Source='" + textBox1.Text + "';Initial Catalog='" + textBox2.Text + "';User ID='" + textBox3.Text + "';Password='" + textBox4.Text + "'"))
        {

             connection.Open();

            if (connection.State == ConnectionState.Open)
            {

                MessageBox.Show("Spojení s databázi problěhlo úspěšně.");
            }
            connection.Close();
            if (connection.State == ConnectionState.Closed)
            {
                MessageBox.Show("Spojení selhalo");
            }
        }

Answer

DGibbs picture DGibbs · Jul 25, 2013

You're using connection.Open = true as if it were a property.

It's a method: connection.Open()

Use the ConnectionState enum to determine if the connection is open or not, eg:

connection.State == ConnectionState.Open