csura
csura

Reputation: 85

how to give connection string in app.config file and how to call it

i used the following code in app.config

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=162.1.6.4;Initial Catalog=Followon_SP;Integrated Security=SSPI" 
     providerName="System.Data.SqlClient"/>

and in form.cs

struct st
{

    public static SqlConnection con;
};
public Mainform()
    {
        InitializeComponent();           
       st.con = new SqlConnection( ConfigurationManager.AppSettings["Connectionstring"].ToString());
    }

but i get the following error in connection open,

Upvotes: 1

Views: 2101

Answers (4)

Mahe&#39;s Vithani
Mahe&#39;s Vithani

Reputation: 11

Read Connection String using following code:

System.Configuration.Configuration rootWebConfig = 
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) {
    connString =
        rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
    if (connString != null)
        Console.WriteLine("Northwind connection string = \"{0}\"", connString.ConnectionString);
    else
        Console.WriteLine("No Northwind connection string");
}

Upvotes: 0

Chris Searles
Chris Searles

Reputation: 2422

You would be much better off using the Entity Framework: http://msdn.microsoft.com/en-us/data/ef.aspx

Add a new data model and VS will take care of all your config settings as long as you have the right username and password to enter in the wizard. Will make your development process a lot easier as well.

Upvotes: 0

marc_s
marc_s

Reputation: 755128

You need to use this instead:

public Mainform()
{
    InitializeComponent();     

    // read out the .ConnectionString property - don't call .ToString() !!
    string cs = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
    st.con = new SqlConnection(cs);
}

Use the ConfigurationManager.ConnectionStrings (not the ConfigurationManager.AppSettings), and then read out the connection string from the .ConnectionString property instead of calling .ToString() on it.

Upvotes: 2

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98840

Set new SqlConnection(cs) to your struct type of con field. Use it like this;

string cs = ConfigurationManager.AppSettings["Connectionstring"].ConnectionString;
st.con = new SqlConnection(cs);

Upvotes: 0

Related Questions