0

I'm trying to make a application that connect to a SQL Server database with connection values from textbox but when I try connect it gives me connection error

error code: 40 - Could not open a connection to SQL server

Here is the source of the application:

private void ConnectToSQL() {
   string connectionString = @"Data Source=" + textBox4.Text + "Initial Catalog=" + textBox1.Text +"User ID=" + textBox2.Text + "Password=" + textBox3.Text;
using (SqlConnection objSqlConnection = new SqlConnection(connectionString)) {
    try {
        objSqlConnection.Open();
        objSqlConnection.Close();
        MessageBox.Show("Connection is successfull");
    } catch (Exception ex) {
        MessageBox.Show("Error : " + ex.Message.ToString());
    }

Please help me with this issue.

Thank you!

3
  • give break point and check the value of connectionstring and paste it here.. Commented Sep 4, 2013 at 5:09
  • 1
    Verify your conntectionstring here Commented Sep 4, 2013 at 5:10
  • 1
    Check out the SqlConnectionStringBuilder class instead of concatenating together your connectino string from textbox input... Commented Sep 4, 2013 at 5:13

2 Answers 2

3

You have missed a semicolon(;) in your connection string. If you append it in your connection string, it should work.

string connectionString = @"Data Source=" + textBox4.Text + 
                           ";Initial Catalog=" + textBox1.Text +
                           ";User ID=" + textBox2.Text + 
                           ";Password=" + textBox3.Text;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I used this .
1

This might be due to you are missing semi columns in your connection string.

Try it as:

string connectionString = @"Data Source=" + textBox4.Text + ";Initial
Catalog=" + textBox1.Text +";User ID=" + textBox2.Text + ";Password="
+ textBox3.Text;

Comments

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.