Introduction
This document explains how to configure a connection string at runtime for a Windows application using C#. This will help the user to switch connections during run time. Also if there are multiple servers and databases, the number of connection strings will be high and a user cannot add everything to the App.config file. This will be helpful for users to use any server and database during run time without the need to create any connection string before execution.
Steps to configure
1. Open Visual Studio and create new a Windows application. (Path : Start -> All Programs -> Microsoft Visual Studio 2005-> Microsoft Visual Studio 2005)
2. Add App.config file to the project.

3. Add the following code in the connection string.
<configuration>
<connectionStrings>
<add name="con" providerName="System.Data.sqlclient" connectionString="" />
</connectionStrings>
</configuration>
4. Now add two text boxes, two labels and a button in the form as shown below.
5. Add a dropdown below to populate a column from a table as shown below.
6. Add "using System.Data.SqlClient;" in the namespace and write the following code in the buttonclick event.
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(txtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(txtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
//In case of VS2010 comment the above line and use the below line
//SqlDataAdapter da = new SqlDataAdapter("select * from employee",Db);
DataTable dt = new DataTable();
da.Fill(dt);
cmbTestValue.DataSource=dt;
cmbTestValue.DisplayMember="Emp_Id";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}

7. Add "using System.Xml; using System.Configuration;" in the name space. Write a new function updateConfigFile with the following code.
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
8. Now build the solution and enter the server name and database. Check that the dropdown is populated correctly. Change database name and click connect again and verify that the new database is connected.
Conclusion
By using the above code, a user can switch over to any server and database at runtime instead of editing app.config file each time for adding a new connection string.

sai jamesPosted Sep 19, 2018, 6:35 AM
Can we modify the connection string in windows service app.config file , after its installed
Dharmendra Kumar PanditPosted Jun 15, 2018, 8:24 AM
Thanks its working fine. Very helpful code.
saagar soniPosted Mar 30, 2017, 9:49 AM
Santosh bhai thanks a lot...your code worked...
Stalin Antony Huallullo CirineoPosted Feb 9, 2017, 5:25 PM
El proyecto esta en C# WPF tengo una ventana echa para poder cambiar de direccion para conectarme a mi base de datos
Stalin Antony Huallullo CirineoPosted Feb 9, 2017, 5:24 PM
Hola, yo estoy intentando cambiar mi archivo App.config en el momento de ejecutarlo para poder instalarlo en cualquier PC y bueno, me podr?an ayudar por favor
SubashPosted Aug 30, 2016, 12:27 PM
Good useful one
ibrahim shaikPosted Apr 2, 2015, 2:10 PM
please replyyy....
ibrahim shaikPosted Apr 2, 2015, 10:50 AM
also, i want to add username and password fields in the windows forms could you let me know how to configure my connection string finally with user entered username,password
ibrahim shaikPosted Apr 2, 2015, 10:48 AM
Hi,When i copied the code in vs2010 its showingg errors at cmbTestValue.DataSource=dt; cmbTestValue.DisplayMember="Emp_Id";
Syeda Mubashira MahboobPosted Mar 27, 2015, 1:18 AM
con.open(); is it required
prabu pmpPosted Nov 12, 2014, 4:59 AM
Hi, it's not changed my xml file connection string, after I closed the application..why..?
shwe myatmonPosted Oct 17, 2014, 5:24 AM
Thanks you so much for your article
Prasenjit DeyPosted Oct 7, 2013, 5:46 AM
nice
Ahmed Al MajedPosted Oct 7, 2013, 5:43 AM
Thanks a lot that's what i'm looking for it but how can I make connection with Username and password. Thanks again for that.
padam thakurPosted Jul 31, 2012, 7:50 AM
Good article can u tell me how to make table in database as variable
Santhosh Kumar JayaramanPosted Jun 26, 2012, 8:24 AM
@Samio. This is because you dont have table employee in the server and database you mentioned
SamioeditedPosted Apr 19, 2012, 8:35 AMEdited Apr 19, 2012, 8:54 AM
I've tested it in Visual Studio 2010, Please add ",Db" as next: SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db); Still cannot connect to the database with this code, I fall in the exception: MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
Stelia JacksonPosted Feb 23, 2012, 11:39 PM
thnx for uploading this article....
Aaron CronjePosted Feb 23, 2012, 12:51 AM
Good Explanation.
Monika AroraPosted Feb 22, 2012, 11:27 PM
Its a very nice and useful article.
Michell JohnsonPosted Feb 22, 2012, 11:02 PM
Hi, Santhosh it's a well explanation about configuring the connection string in App.config file at run time and very helpful to us, Thanks for sharing.....
James LerdorfPosted Feb 22, 2012, 10:50 PM
Thanks for this nice article, keep it up.