Code Snippets

  

VB.NET Source Code


Welcome to Dream.In.Code
Getting VB.NET Help is Easy!

Join 131,931 VB.NET Programmers for FREE! Get instant access to thousands of VB.NET experts, tutorials, code snippets, and more! There are 1,727 people online right now. Registration is fast and FREE... Join Now!





Get connection string from app.config

I use this function in my applications to retrieve the connection string from the app.config file. It is especially handy in the application I'm working on now as there are 2 databases it can connect to.

Submitted By: PsychoCoder
Actions:
Rating:
Views: 10,302

Language: VB.NET

Last Modified: August 2, 2007
Instructions: Store your connection stirng in the app.config like this:

< connectionStrings >
< add name="YourName"
connectionString="Persist Security Info=False;Data Source=Database_Name;Initial Catalog=Table_Name;Integrated Security=SSPI;Trusted_Connection=TRUE;Application Name=Application_Name"
providerName="System.Data.SqlClient" />
< /connectionStrings >
To use:

Dim SqlConnection As New SqlConnection("GetConnectionString("YourName"))

Snippet


  1. Public Shared Function GetConnectionString(ByVal strConnection As String) As String
  2.    'Declare a string to hold the connection string
  3.    Dim sReturn As New String("")
  4.    'Check to see if they provided a connection string name
  5.    If Not String.IsNullOrEmpty(strConnection) Then
  6.       'Retrieve the connection string fromt he app.config
  7.       sReturn = ConfigurationManager. & _
  8.       ConnectionStrings(strConnection).ConnectionString
  9.    Else
  10.       'Since they didnt provide the name of the connection string
  11.        'just grab the default on from app.config
  12.       sReturn = ConfigurationManager. & _
  13.       ConnectionStrings("YourConnectionString").ConnectionString
  14.    End If
  15.    'Return the connection string to the calling method
  16.    Return sReturn
  17. End Function

Copy & Paste


Comments


jimall2001 2008-11-05 08:51:28

Thank you for the snippet It worked great.


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live VB.NET Help!

VB.NET Tutorials

Reference Sheets

VB.NET Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month