Nim
Nim

Reputation: 376

App.Config setting to ComboBox

Here below is App.Config Code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <appSettings>
        <add key="DBServer" value="Localhost"/>
        <add key="DBServer" value="Sql2005rs"/>
        <add key="DBName" value="Everest"/>
   </appSettings>
</configuration>

I Am trying to get the values Local Host and Sql2005rs to return in a combo box this is what I'm using can anyone tell me why it is failing.

public Form1()
{
    InitializeComponent();
        var DBServerNames = ConfigurationManager.AppSettings.AllKeys .Where(key => key.StartsWith("DBServer")) .Select (key => ConfigurationManager.AppSettings[key]) .ToArray();
        DBServer.Items.AddRange(DBServerNames);
}

Yet it only return sql2005rs anyone know why?

Upvotes: 0

Views: 5389

Answers (1)

Darren Wainwright
Darren Wainwright

Reputation: 30747

You will always get the last one when you have multiple settings with the same key. When you have multiple of the same key each one gets overridden by the next.

So rather than do that, which really isn't a very good thing to do - the key is supposed to be unique, as in any key/value dictionary - change your settings to something like :

<appSettings>
        <add key="DBServers" value="Localhost,Sql2005rs"/>
        <add key="DBName" value="Everest"/>
   </appSettings>

Then just pluck out the DBServers value and parse that. Something like:

string[] myServers= ConfigurationManager.AppSettings["DBServers"].Split(',');

Upvotes: 1

Related Questions