VB.NET Connection String (Web.Config, App.Config)

Really with annoying time with connection strings.

I have two projects together in one solution. A web form application that acts as a presentation layer, and a class library that supports it, which will send and receive data from the database.

- An employee class within the class library project -

Friend Class Employee Public Function GetEmployees() As DataSet Dim DBConnection As New SqlConnection(My_ConnectionString) Dim MyAdapter As New SqlDataAdapter("exec getEmployees", DBConnection) Dim EmployeeInfo As DataSet MyAdapter.Fill(EmployeeInfo, "EmployeeInfo") Return EmployeeInfo End Function End Class 

Currently, the application tells me that it cannot access the "My_ConnectionString", which I tried to save in the configuration file for quick re-access:

 <configuration> <system.web> <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <connectionStrings> <add name="My_ConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=My_DB;Integrated Security=True;"/> </connectionStrings> </configuration> 

Web.config is part of a web form project, not a class library, are these projects unable to "talk" to each other? Do I need to add a web application configuration file to the class library to store the connection string in this project?

+6
source share
4 answers

It's not clear where My_ConnectionString comes from in your example, but try

System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString

like this

 Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString) 
+14
source

If during creation the .mdf database and connection string were saved, you should have access to it through:

  Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString) 

Hope this helps someone.

+4
source
 Public Function connectDB() As OleDbConnection Dim Con As New OleDbConnection 'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & "" Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD" Try Con.Open() Catch ex As Exception showMessage(ex) End Try Return Con End Function 
0
source

Connection in APPConfig

 <connectionStrings> <add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" /> </connectionStrings> 

In Class.Cs

 public string ConnectionString { get { return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); } } 
0
source

All Articles