如果您需要“超级动态”,那么 Davio 有正确的选择。
如果您需要“我有 N 个数据库,可能会不时更改”,那么我建议:
以下是典型的 Dot Net 2.0 及以上配置。
<connectionStrings>
<add name="EastCoastConnectionString" connectionString="server=server01;database=myDb;uid=myUser;password=myPass;" />
<add name="WestCoastConnectionString" connectionString="server=server02;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
然后创建一个自定义配置部分,将“友好名称”映射到连接字符串。
查找此代码:
如何在 ConfigurationSection 中包含简单集合
<TransformationToDirectoryMappingsSection>
<TransformationToDirectoryMappings>
<add FriendlyName="NY Giants" PickupFolder="EastCoastConnectionString" />
<add FriendlyName="NE Patriots" PickupFolder="EastCoastConnectionString" />
<add FriendlyName="Carolina Panthers" PickupFolder="EastCoastConnectionString" />
<add FriendlyName="San Francisco 49ers" PickupFolder="WestCoastConnectionString" / >
<add FriendlyName="Seattle Seahawks" PickupFolder="WestCoastConnectionString" />
<add FriendlyName="Arizona Cardinals" PickupFolder="WestCoastConnectionString" />
</TransformationToDirectoryMappings>
</TransformationToDirectoryMappingsSection>
</configuration >
然后用所有“FriendlyName”填充一个下拉框......然后您可以将其映射回连接字符串。
现在,您可以使用连接字符串的名称填充下拉列表......但我不喜欢这个想法......我更喜欢“友好名称”到“实际名称”的映射。
至少,在您的配置文件中设置连接字符串.....,并使用以下内容填充您的下拉列表:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx
ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings connection in connections)
{
string name = connection.Name;
}