Click here to Skip to main content
15,748,748 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I retrieve my connection string from my app config?

here is my app config:

<?xml version="1.0"?>
        <add name="SqlConnectionString" connectionString="Data Source=(local);Initial Catalog=retriever;User ID=sa" providerName="System.Data.SqlClient"/>
    <supportedRuntime version="v2.0.50727"/></startup>

here is my code:

public SqlConnection SQcon = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionString"];
       public SqlCommand SQcmd;
       public SqlDataReader SQread;
       public SqlDataAdapter SQadapt;
       public SqlException SQexcept;
       public string SQdatasource = "SELECT * FROM dbo.Tick_Inventory ORDER BY invoiceDate_time";
       public int ProductCountHolder;
       public string Tickets;

however im getting an error
public SqlConnection SQcon = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionString"];

how to fix this?

ConnectionStrings collection does not return the SqlConnection object. It is a string. What you need is:

SqlConnection connection = new SqlConnection (ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
Share this answer
JB0301 4-Mar-14 3:10am    
It's not working either
dan!sh 4-Mar-14 3:13am    
What error do you get?
dan!sh 4-Mar-14 3:15am    
Check the updated reply.
try this..

SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
Share this answer
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
Share this answer
ErBhati 4-Mar-14 7:12am    
plz select as answer for others if it helps you....
CHill60 4-Mar-14 8:51am    
It would be a little unfair of the OP to accept your answer as it is identical to solution 2 that was posted an hour earlier than yours

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900