Click here to Skip to main content
15,114,081 members
Articles / Programming Languages / C#
Tip/Trick
Posted 26 Jun 2012

Tagged as

Stats

180.1K views
5.9K downloads
27 bookmarked

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

Rate me:
Please Sign up or sign in to vote.
4.79/5 (12 votes)
28 Jun 2012CPOL1 min read
How to configure a connection string at runtime for a Windows application using C#

Introduction

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)

    Image 1

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

    Image 2

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

    Image 3

  4. Now add two text boxes, two labels, and a button in the form as shown below:

    Image 4

  5. Add a dropdown below to populate a column from a table as shown below:

    Image 5

  6. Add “using System.Data.SqlClient;” in the namespaces area and write the below code in the buttonclick event:
    C#
    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",Db);
    C#
     SqlDataAdapter da = new SqlDataAdapter("select * from employee");//incase earlier Visualstudios
        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");
    }

    Image 6

  7. Add “using System.Xml; using System.Configuration;” in the namespaces section. Write a new function updateConfigFile with the following code:
    C#
    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);
    }

    Image 7

  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.

    Image 8

    Image 9

Conclusion

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.

License

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

Share

About the Author

Santhosh Kumar Jayaraman
Technical Lead EF (Education First)
India India
I graduated as Production Engineer and started my career as Software Developer then worked as tester for a while before moving into Windows application development using Microsoft Technologies. But for the last few years i am working on javascript, React, Node, AWS, Azure Chatbots

Comments and Discussions

 
QuestionThanks Pin
MarcusCole68335-Feb-16 9:50
professionalMarcusCole68335-Feb-16 9:50 
QuestionI get "system nullreferenceexception" error when run the code Pin
Daniel v S23-Nov-15 21:18
MemberDaniel v S23-Nov-15 21:18 
Questionwarning error: The index being passed in is out of range Pin
Member 245846728-Oct-14 21:37
MemberMember 245846728-Oct-14 21:37 
QuestionMultiple SQL Server connection strings Pin
Arjunwalmiki15-Jan-14 20:23
MemberArjunwalmiki15-Jan-14 20:23 
QuestionRequired Help Pin
AnilC20-Aug-13 2:58
MemberAnilC20-Aug-13 2:58 
GeneralMy vote of 5 Pin
Akash_shukla7-Jan-13 9:42
MemberAkash_shukla7-Jan-13 9:42 
GeneralMy vote of 5 Pin
daghune20-Nov-12 20:03
Memberdaghune20-Nov-12 20:03 
SuggestionAn easy way to modify each app.setting Pin
Daniel Leykauf29-Jun-12 4:24
MemberDaniel Leykauf29-Jun-12 4:24 
Hi,

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:
VB
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:
VB
My.Settings.ModifySetting("MyConString", "Data Source=C:\newDB.dbf")


That's all.

Daniel
GeneralReally? Pin
Vitaly Tomilov28-Jun-12 9:43
MemberVitaly Tomilov28-Jun-12 9:43 
Suggestionvalid as long as... Pin
VallarasuS28-Jun-12 4:17
MemberVallarasuS28-Jun-12 4:17 

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

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