Connection String at run time
i want to develop a connection string at run time.How i can do this.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Shakuntala GaurPosted May 28, 2012, 6:58 PM
This is how you can make connection string dynamic:
Use the settings.settings to store and create the connection string ( which updates also the app.config ), then change the code of the settings.cs (to create this file automatically simply hit the button "View Code" in the setting designer buttons bar) ovveriding public override object this[string propertyName]
Assuming the setting name for your connection string is "ConStr"
internal sealed partial class Settings {
public Settings()
{
// To add event handlers for saving and changing settings, uncomment the lines below:
// this.SettingChanging += this.SettingChangingEventHandler;
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
{
// Add code to handle the SettingChangingEvent event here.
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
// Add code to handle the SettingsSaving event here.
}
public override object this[string propertyName]
{
get
{
if (propertyName == "ConnStr")
{
return GetConStr(); // GetConStr retrive the run time value for the connection string
}
return base[propertyName];
}
set
{
base[propertyName] = value;
}
}
private string GetConnStr()
{
string connstr;
// build your connStr here
return connStr;
}
}