Question

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!

Was it helpful?

Solution

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;

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top