Reputation: 2835
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,
Upvotes: 0
Views: 2622
Reputation: 602
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.
Upvotes: 2
Reputation: 216243
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";
Upvotes: 1