简体   繁体   中英

ADO.NET : Error occurred while establishing a connection to SQL Server

i am trying to bind data to Gridview and getting this error

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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

this is my simple code

 string cs = "data source =.; initial catalog= MyDB;  integrated security= SSPI";
 SqlConnection con = new SqlConnection(cs);
 SqlCommand cmd = new SqlCommand("select * from tbl_Dept", con);
 con.Open();
 GridView1.DataSource = cmd.ExecuteReader();
 GridView1.DataBind();
 con.Close();   

in SQl management studio i have rechecked db name and its same as mentioned in code

I found some related questions but those did not work for me so posting mine one , Please help me with it,

You can define SqlConnection string in your web.config(in web applications) or app.config(in windows form application). Simply define like this -

<configuration>
    <connectionStrings>
         <add name="Connection" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial   Catalog=DBName;Trusted_connection=yes;User ID=''; Password=''"/
    </connectionStrings>
</configuration>

then access this code in you .cs form using

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString.ToString());

and after this you can use SqlConnection object con in you whole form.

When you install SQL Server Express the setup propose to create a named instance , and by default, this named instance, is called SQLEXPRESS.

When you want to connect to this named instance it is required to specify the name.
So, in your case your connection string should be changed to

"Data Source =.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM