从C#代码更改连接字符串?

时间:2011-12-15 06:37:37

标签: c# silverlight config

有没有办法以编程方式更改连接字符串?我的意思是用户可以使用组合框选择他想要使用的网站,并在该特定网站上加载用户?

配置代码如下

<add key ="sampleconnectionstring" value="Server=sampleserver;Database=sampledb;User ID=sampleid;Password=samplepassword;Trusted_Connection=False;Encrypt=True;"/>
<add key ="sampleconnectionstring1" value="Server=sampleserver1;Database=sampledb1;User ID=sampleid1;Password=samplepassword;Trusted_Connection=False;Encrypt=True;"/>
<add key ="sampleconnectionstring2" value="Server=sampleserver2;Database=sampledb2;User ID=sampleid2;Password=;Trusted_Connection=False;Encrypt=True;"/>
<add key ="sampleconnectionstring3" value="Server=sampleserver3;Database=sampledb3;User ID=sampleid3;Password=samplepasswrd;Trusted_Connection=False;Encrypt=True;"/>

是否有一个程序设计(如果这是一个单词)的方式在这个连接字符串之间切换取决于组合框中的选定项目?任何帮助,将不胜感激。感谢。

6 个答案:

答案 0 :(得分:2)

根据您对数据库使用的内容,您可以加载加载时所需的任何连接字符串。

例如实体框架

Entities model = new Entities(connectionString);

对于ADO.NET

  using (SqlConnection connection =
        new SqlConnection(connectionString))
    {

    }

对于Linq To SQL

使用:

MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);

对于LinqDataSource,拦截ContextCreating事件并手动创建DataContext,如上所述:

protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
{
    e.ObjectInstance = new MyDataClassesDataContext (dynamicConnString);
}

(Linq to SQL示例取自:Linq to Sql - Set connection string dynamically based on environment variable

答案 1 :(得分:0)

它有一种方法,只需在Combobox上设置连接字符串selectedindex已更改事件。请参阅以下代码。首先将默认连接字符串设置为appconfig中的第一个字符串,因为在表单加载时,不会触发selectedindexchanged事件。获取连接的ConnString,因为它是一个可以访问的公共属性。

    public string ConnString { get; set; }
    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (CBox.SelectedIndex == 0)
        {
            ConnString = getAppSetting("sampleconnectionstring");
        }
        else if (CBox.SelectedIndex == 1)
        {
            ConnString = getAppSetting("sampleconnectionstring1");
        }
        else if (CBox.SelectedIndex == 2)
        {
            ConnString = getAppSetting("sampleconnectionstring2");
        }
        else if (CBox.SelectedIndex == 3)
        {
            ConnString = getAppSetting("sampleconnectionstring3");
        }
    }
    private string getAppSetting(string strKey)
    {
        string strValue = string.Empty;
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.XmlResolver = new XmlXapResolver();
        XmlReader reader = XmlReader.Create("ServiceReferences.ClientConfig");
        reader.MoveToContent();
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element && reader.Name == "add")
            {
                if (reader.HasAttributes)
                {
                    strValue = reader.GetAttribute("key");
                    if (!string.IsNullOrEmpty(strValue) && strValue == strKey)
                    {
                        strValue = reader.GetAttribute("value");
                        return strValue;
                    }
                }
            }
        }
        return strValue;
    }

    private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
    {
        ConnString = getAppSetting("sampleconnectionstring");

    }

答案 2 :(得分:0)

如果每个键与一个组合框项目的值相等,您可以直接按键选择连接字符串。

答案 3 :(得分:0)

您可以使用configurationmanager connectionstring collection获取列表。 然后,您可以将组合框绑定到它。类似的东西:

<ComboBox ItemsSource={Binding ConnectionStrings} DisplayMemberPath="Name" SelectedItem={Binding Path=SelectedConnectionString, Mode=TwoWay} /> 

答案 4 :(得分:0)

请记住,连接字符串只是一个字符串。您可以将其他字符串连接到它:

string CreateConnectionString(string server, string sampledb,  string userid, string password)
{
   return string.Format("Server={0};Database={1};User ID={2};Password={3}Trusted_Connection=False;Encrypt=True;",server,sampledb,userid,password);

}

答案 5 :(得分:0)

如果我没错,你必须在web.config文件中这样做。

<appSettings>
     <add key = "sampleconnectionstring" ..../>
     <add key = "sampleconnectionstring1" ..../>
     <add key = "sampleconnectionstring2" ..../>
     <add key = "sampleconnectionstring3" ..../>
</appSettings>

并且您想以编程方式更改字符串。

所以,你可以这样做---- 首先,你可以将键名保存在组合框的值字段中。 然后,在dropdown / combo框中选择索引,改写如下所示...

  protected void ddlUrDropdown_SelectedIndexChanged(object sender, EventArgs e)
  {
        // Checking whether first Item "Select......." (index = 0) is selected or not.
        if (ddlUrDropdown.SelectedIndex != 0)
        {
            // Getting the Selected "Country_Id".
            string keyName = ddlUrDropdown.SelectedValue;
            string connectionString = ConfigurationSettings.AppSettings[keyName];
            // Where keyName can take values like- "sampleconnectionstring" or "sampleconnectionstring1" or "sampleconnectionstring2" or "sampleconnectionstring3"
            // After getting the connection string according to selected item of combo box, u can create connection and do whatever u want, like below...
            using(SqlConnection connection = new SqlConnection(connectionString))
            {
                  connection.Open();
                  // perform work with connection
             }         
        }
        // Error Message displayed when first Item "Select......." (index = 0) is selected.
        else
        {
            lblError.Text = "Select any item .";
        }
    }