user710502
user710502

Reputation: 11471

My Windows Forms program is not finding the 'app.configconnecetion' string

I am new to Windows Forms and I modified the app.config file to have some connection strings, but it never finds it when I use it in code; it retuns null.

<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <connectionStrings>
            <add name="MySqlConnectionString" connectionString="server=localhost;database=mydatabase;uid=root;" />
        </connectionStrings>
    </configuration>

Also I use this code to see if it's pulling something

 string val = System.Configuration.ConfigurationSettings.AppSettings["MySqlConnectionString"];

but val is null. Also, under the system.configuration stuff, it says that it's obsolete and prompts me to use System.Configuration.ConfigurationManager.AppSettings, but the IntelliSense does not give me option "ConfigurationManager", I only have ConfigurationSettings. I tried typing it and see if the little blue underline came up to include something but nothing comes up.

What could I be doing wrong?

Upvotes: 0

Views: 583

Answers (1)

Timeout
Timeout

Reputation: 7909

This is because you're trying to use AppSettings when it's not in AppSettings.

Also make sure your reference to System.Configuration is correct.

  • Go into your project, right click References -> Add Reference -> .NET -> Go down to System.Configuration and add it.

You'll need to switch to this:

ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;

This should help illustrate the difference between AppSettings and ConnectionStrings:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="MySqlConnectionString" connectionString="server=localhost;database=mydatabase;uid=root;" />
  </connectionStrings>
  <appSettings>
    <add key="MyAppSetting" value="Hello World!"/>
  </appSettings>
</configuration>

And then from C#:

ConfigurationManager.AppSettings["MyAppSetting"]

Upvotes: 2

Related Questions