Search code examples
c#sql-serversqlconnection

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!


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;