Click here to Skip to main content
Click here to Skip to main content

Tagged as

Configuring a Connection String in the App.Config File During Runtime in C#

, 28 Jun 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to configure a connection string at runtime for a Windows application using C#


This document covers how to configure a connection string at runtime for a Windows application using C#. This will help the user to switch connections during runtime. Also if there are multiple servers and databases, the number of connection strings will be high and the user cannot add everything in the App.config file. This will be helpful for users who might use a random server and database during runtime and there is no need to create a connection string beforehand.

Steps to Configure

  1. Open Visual Studio and create a new Windows application. (Path : Start -> All Programs -> Microsoft Visual Studio 2010-> Microsoft Visual Studio 2010)

  2. Add the App.config file to the project.

  3. Add the below code in the connection string:
    <add name="con" providerName="System.Data.sqlclient" connectionString="" />

  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 namespaces area and write the below code in the buttonclick event:
        //Constructing connection string from the inputs
        StringBuilder Con = new StringBuilder("Data Source=");
        Con.Append(";Initial Catalog=");
        Con.Append(";Integrated Security=SSPI;");
        string strCon = Con.ToString();
        //Create new sql connection
        SqlConnection Db = new SqlConnection();
        //to refresh connection string each time else it will use previous connection string
        Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
        //To check new connection string is working or not
        SqlDataAdapter da = new SqlDataAdapter("select * from employee",Db);
     SqlDataAdapter da = new SqlDataAdapter("select * from employee");//incase earlier Visualstudios
        DataTable dt = new DataTable();
    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 namespaces section. 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
        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

  8. Now build the solution and enter the server name and database. Check dropdown is populated correctly. Change database name and click Connect again and verify the new database is connected.


By using the above code, the user can switch over to any server and database at runtime instead of editing the app.config file each time for adding a new connection string.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Santhosh Kumar Jayaraman
Software Developer Radiometer
India India
I have great passion towards Microsoft technologies. I have experience in Microsoft technologies like WPF, WCF, ASPNET, WinForms,Silverlight, VB.NET, C-Sharp, Entity framework,SSRS, LINQ, Extension methods and SQL server. I started with my career in Infosys in the year 2009 and i worked with Trigent, Education First (EF) in the recent years before joining my current company Radiometer.

Comments and Discussions

Questionwarning error: The index being passed in is out of range PinmemberMember 245846728-Oct-14 21:37 
QuestionMultiple SQL Server connection strings PinmemberArjunwalmiki15-Jan-14 20:23 
QuestionRequired Help PinmemberAnilC20-Aug-13 2:58 
GeneralMy vote of 5 Pinmembermaxsshukla7-Jan-13 9:42 
GeneralMy vote of 5 Pinmemberdaghune20-Nov-12 20:03 
SuggestionAn easy way to modify each app.setting PinmemberDanielLey29-Jun-12 4:24 
If you want to modify the application settings also at runtime, a simple approach could be as follow:
1. Create a new partial class with same namespace and name as of your original "settings.designer" file.
2. Add in this class a method to modify your setting.
A sample class could look like:
Namespace My
    Friend Partial Class MySettings
        Friend Sub ModifySetting(ByVal SettingName As String, ByVal Value As String)
            Me(SettingName) = Value
        End Sub
    End Class
End Namespace
To change an application setting you will have now only to call the method:
My.Settings.ModifySetting("MyConString", "Data Source=C:\newDB.dbf")
That's all.
GeneralReally? PinmemberVitaly Tomilov28-Jun-12 9:43 
Suggestionvalid as long as... [modified] PinmemberVallarasuS28-Jun-12 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150326.1 | Last Updated 28 Jun 2012
Article Copyright 2012 by Santhosh Kumar Jayaraman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid