C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 300,308 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,080 people online right now. Registration is fast and FREE... Join Now!





Get connection string from the web.config

This is a snippet I use to retrieve my database connection string I store in the web.config file.

Submitted By: PsychoCoder
Actions:
Rating:
Views: 41,267

Language: C#

Last Modified: January 20, 2008
Instructions: Pass the method and it will return the connection string for that name (works well if you have multiple connections in the config file) and it will retrieve that specific connection string.

If you fail to provide the name of a connection string it will default to your default (usually 1st in the list) to the default string.

Snippet


  1. #region GetConnectionstring
  2. /// <summary>
  3. /// method to retrieve connection stringed in the web.config file
  4. /// </summary>
  5. /// <param name="str">Name of the connection</param>
  6. /// <remarks>Need a reference to the System.Configuration Namespace</remarks>
  7. /// <returns></returns>
  8. public string GetConnectionString(string str)
  9. {
  10.     //variable to hold our return value
  11.     string conn = string.Empty;
  12.     //check if a value was provided
  13.     if (!string.IsNullOrEmpty(str))
  14.     {
  15.         //name provided so search for that connection
  16.         conn = ConfigurationManager.ConnectionStrings[str].ConnectionString;
  17.     }
  18.     else
  19.         //name not provided, get the 'default' connection
  20.     {
  21.         conn = ConfigurationManager.ConnectionStrings["YourConnName"].ConnectionString;
  22.     }
  23.     //return the value
  24.     return conn;
  25. }
  26. #endregion 
  27.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


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





Live C# Help!

Be Social

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

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month