xeLin xel
xeLin xel

Reputation: 49

SQL Server : database connection with textbox values

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!

Upvotes: 0

Views: 6067

Answers (2)

C Sharper
C Sharper

Reputation: 8626

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;

Upvotes: 1

sarwar026
sarwar026

Reputation: 3821

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;

Upvotes: 3

Related Questions