0

i am having an error while connecting the local service database of C# in VS 2017. The app is just for testing and the error i am having the con.open() line. I have placed a data gridview in the app with dataset and it is showing all the values inside the db in gridview but when i use my button to execute the INSERT Query it shows up an error. This is the error below

System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid. )'

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C: \\Users\\Shahrukh Khan\\source\\repos\\checkingsetup\\testingdb\\Database123.mdf;Integrated Security=True");

private void button2_Click(object sender, EventArgs e)
{
    listBox1.Items.Add(textBox1.Text);

    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "insert into table1 values('"+textBox1.Text+"')";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "select * from table1";
    cmd.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    dataGridView1.DataSource = dt;
    con.Close();
}
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
  • Possible duplicate of [Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?](https://stackoverflow.com/questions/1391503/why-did-a-network-related-or-instance-specific-error-occur-while-establishing-a) – gunr2171 Aug 07 '18 at 15:26
  • 2
    You have a space after `C:` in your connection string. – gunr2171 Aug 07 '18 at 15:27
  • That connection string is wrong; you want either `"...\\MSSQLLocalDB;..."` or `@"...\MSSQLLocalDB;..."`, not both. – Dour High Arch Aug 07 '18 at 17:07

0 Answers0