Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Click Here
Getting C# Help is Easy!

Join 118,589 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 816 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! 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: 10,985

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!

C# Tutorials

Reference Sheets

C# 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