ARTICLE

Configuring Connection String in App.Config File During Runtime For a C# Windows Application

Posted by Santhosh Kumar Jayaraman Articles | Windows Forms C# February 22, 2012
This document explains how to configure a connection string at runtime for a Windows application using C#.
Reader Level:
 

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)

App.Config1.gif

2. Add App.config file to the project.

App.Config2.gif

App.Config3.gif

3. Add the following code in the connection string.

<configuration>
              <
connectionStrings>
<
add name="con" providerName="System.Data.sqlclient" connectionString="" />
          </connectionStrings>
</configuration>

App.Config4.gif

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

App.Config5.gif

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

App.Config6.gif

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


App.Config7.gif

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

App.Config8.gif

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.

App.Config9.gif

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.  

Login to add your contents and source code to this article
Article Extensions
Contents added by le Ha on May 18, 2013
thanks you
post comment
     

Good article can u tell me how to make table in database as variable

Posted by padam thakur Jul 31, 2012

@Samio. This is because you dont have table employee in the server and database you mentioned

Posted by Santhosh Kumar Jayaraman Jun 26, 2012

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

Posted by Samio Apr 19, 2012

thnx for uploading this article....

Posted by Stelia Jackson Feb 23, 2012

Good Explanation.

Posted by Aaron Cronje Feb 23, 2012
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.