Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Really having an annoying time with connection strings.

I have two projects together in a single solution. A Web forms application acting as the presentation layer, and a class library supporting it which will send and receive data from a database.  

-- The 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 is telling me it cannot access "My_ConnectionString" which I have attempted to store within a config file for quick repeated 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>

The web.config is part of the web form project and not the class library, are these projects unable to 'talk' to each other? Do I need to add a web / app config file to the class library to store a connection string within that project?

like image 601
Corgalas Avatar asked Mar 16 '13 06:03

Corgalas


3 Answers

Not clear where My_ConnectionString is coming from in your example, but try this

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

like this

Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)
like image 50
G. Stoynev Avatar answered Nov 03 '22 18:11

G. Stoynev


If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:

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

Hope that helps someone.

like image 5
Dave Avatar answered Nov 03 '22 18:11

Dave


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();
    }
}
like image 1
samir Avatar answered Nov 03 '22 19:11

samir