Click here to Skip to main content
15,890,973 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:

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


here is my code:

C#
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
on
C#
public SqlConnection SQcon = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionString"];


how to fix this?
Posted

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

C#
SqlConnection connection = new SqlConnection (ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
 
Share this answer
 
v2
Comments
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
 
C#
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
 
Share this answer
 
Comments
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