I've never used the "appSettings" before. How do you configure this in C# to use with a SqlConnection, this is what I use for the "ConnectionStrings"
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
And this is what I have for the "appSettings"
SqlConnection con = new SqlConnection();
con = ConfigurationManager.AppSettings("ConnectionString");
but it is not working.
This question is related to
c#
asp.net
sql
sqlconnection
you should use []
var x = ConfigurationManager.AppSettings["APIKey"];
\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this
<add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />
In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have
con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
Your web.config
file should have this structure:
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="..." />
</connectionStrings>
</configuration>
Then, to create a SQL connection using the connection string named MyConnectionString
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
If you'd prefer to keep your connection strings in the AppSettings
section of your configuration file, it would look like this:
<configuration>
<appSettings>
<add key="MyConnectionString" value="..." />
</appSettings>
</configuration>
And then your SqlConnection constructor would look like this:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);
Source: Stackoverflow.com