2

Is there any way to change a connection string programatically? I mean user can pick which site he wants to use using a combobox, and load users on that particular site?

code for config as follows

<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;"/>

is there a programmatical(if that's a word) way of changing between this connection strings depending on the selected item in the combo box? Any help would be appreciated. Thanks.

Nathan
  • 1,520
  • 1
  • 12
  • 21
  • Maybe I misread your question. I think you have three questions here: 1. how to retrieve the connection strings? 2. how to bind it to a combo box? 3. how to set the selected connection string? Please clarify what's the problem... – Yuval Peled Dec 15 '11 at 06:56
  • @YuvalPeled I can retrieve the connection strings. I can bind them to the combo box. So particularly, my problem lies in your question number 3. Thanks for the help. – Nathan Dec 15 '11 at 07:02

6 Answers6

2

Depending on what you are using for the database you can load any connection string you want when loading.

For entity framework for example

Entities model = new Entities(connectionString);

For ADO.NET

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

    }

For Linq To SQL

Use:

MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);

For a LinqDataSource, intercept the ContextCreating event and create the DataContext manually as above:

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

(Linq to SQL example taken from: Linq to Sql - Set connection string dynamically based on environment variable

Community
  • 1
  • 1
Adam
  • 16,089
  • 6
  • 66
  • 109
  • You can load your connection strings from anywhere, I assume you know how to load them in a combo box? Then it is just taking the selectedvalue and putting it in the connectionString variable as shown above. – Adam Dec 15 '11 at 06:55
  • I am currently using DBML and Linq to SQL. So is there any code for that? I'm practically new to this, I'm sorry. – Nathan Dec 15 '11 at 07:00
  • Thats a trickier one. Luckily someone answered it on StackOverflow already: http://stackoverflow.com/a/1188971/540339 . Does that work for you? – Adam Dec 15 '11 at 07:05
  • I'm definitely gonna try that out. Thanks a lot. – Nathan Dec 15 '11 at 07:07
0

Its there a way, just set the connection string on Combobox selectedindex changed event. See the below code. First set the default connection string as the first string in appconfig, because at form load the selectedindexchanged event will not fire. Get the ConnString for the connection where ever you want, because its a public property that can be accessable.

    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");

    }
0

Your can select connection strings by key directly if each the key is equal with the value of one of your combobox items.

0

You can get the list by using the configurationmanager connectionstring collection. Then you can bind the combo box to it. something like:

<ComboBox ItemsSource={Binding ConnectionStrings} DisplayMemberPath="Name" SelectedItem={Binding Path=SelectedConnectionString, Mode=TwoWay} /> 
Yuval Peled
  • 4,988
  • 8
  • 30
  • 36
0

Remember that the connection string is just a string. You can concatenate other string to it:

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);

}
Lucian
  • 3,407
  • 2
  • 21
  • 18
  • where do i return this? how do I put this in the Web.config file? sorry, I'm new to this. – Nathan Dec 15 '11 at 06:52
  • ah ok. I'm not that good at Silverlight and services to answer your question. I was just giving you an example to show you that it is possible to create a connection string on the fly. You don't have to use my code. – Lucian Dec 15 '11 at 06:58
0

If I am not wrong, u must be doing like this in web.config file.

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

and u want to change the strings programmatically.

So, u can do it like this---- first of all u can keep the key names in the value field of the combo box. Then, in dropdown/combo box selected index changed write like below...

  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 .";
        }
    }      
Tadit Dash
  • 305
  • 23
  • 60
  • 141