Code Snippets

  

VB.NET Source Code


Welcome to Dream.In.Code
Become a VB.NET Expert!

Join 149,073 VB.NET Programmers for FREE! Get instant access to thousands of VB.NET experts, tutorials, code snippets, and more! There are 1,317 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: 12,352

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.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live VB.NET Help!

VB.NET Tutorials

Reference Sheets

VB.NET Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month