<configuration> <connectionStrings> <add name="con" providerName="System.Data.sqlclient" connectionString="" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> </configuration>first," /> <configuration> <connectionStrings> <add name="con" providerName="System.Data.sqlclient" connectionString="" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> </configuration>first," />
c# tutorials

Updated : Oct 18, 2019 in Articles

How to change connectionstring in app.config dynamically

In this article, We will Learn About how to change connectionstring in app.config dynamically from scratch

change connection string in app.config dynamically
change connection string in app.config dynamically

Change the connectionstring at run time in App.config dynamically

Add the following given code in your App.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
<add name="con" providerName="System.Data.sqlclient" connectionString="" />
</connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
</configuration>

first, you will load your SQL server instance name and then bind at form_load following the given below code

private void Form1_Load(object sender, EventArgs e)
        {
            cboServer.Items.Add(".");
            cboServer.Items.Add("(local)");
            cboServer.Items.Add(@".\SQLEXPRESS");
            cboServer.Items.Add(string.Format(@"{0}\SQLEXPRESS", Environment.MachineName));
            cboServer.SelectedIndex = 3;
            cmbAuthentication.Items.Add("SQL Server Authentication");
            cmbAuthentication.Items.Add("Windows Authentication");
            cmbAuthentication.DropDownStyle = ComboBoxStyle.DropDownList;
        }

Right-click authentication Combobox go to properties and then go to events double click on SelectedValueChanged event add the given below code

private void cmbAuthentication_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbAuthentication.Text == "SQL Server Authentication")
            {
                txtUserName.Enabled = true;
                txtPassword.Enabled = true;
            }
            if (cmbAuthentication.Text == "Windows Authentication")
            {
                txtUserName.Text = "";
                txtPassword.Text = "";
                txtUserName.Enabled = false;
                txtPassword.Enabled = false;
                eplogin.Clear();
            }
        }

Go to toolBox search for error provider drag and drop on your form change the name as eplogin this error provider for validating username, password and SQL server name if authentication mode is SQL server

Add the given below method it will change connectionstring at runtime in app.config

 public void updateAppConfigFile(string con)
        {
            XmlDocument objXmlfile= new XmlDocument();
            objXmlfile.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            foreach (XmlElement xElement in objXmlfile.DocumentElement)
            {
                if (xElement.Name == "connectionStrings")
                {
                    xElement.FirstChild.Attributes[2].Value = con;
                }
            }
            objXmlfile.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

Double click on connect button add following code in btnconnectionstring_Click

 private void btnconnectionstring_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder Con = new StringBuilder("Data Source=");
                Con.Append(cboServer.Text);
                Con.Append(";Initial Catalog=");
                Con.Append(txtDataDaseName.Text);
                Con.Append(";Integrated Security=True;");
                if (cmbAuthentication.Text == "SQL Server Authentication")
                {
                    bool errorflag = false;
                    eplogin.Clear();
                    if (txtUserName.Text.Trim() == "")
                    {
                        errorflag = true;
                        eplogin.SetError(txtUserName, "Please provide User Name");

                    }
                    if (txtPassword.Text.Trim() == "")
                    {
                        errorflag = true;
                        eplogin.SetError(txtPassword, "Please provide password");

                    }
                    if (cboServer.Text.Trim() == "")
                    {
                        errorflag = true;
                        eplogin.SetError(cboServer, "Please provide password");

                    }
                    if (errorflag == false)
                    {
                        Con.Append("ID=");
                        Con.Append(txtUserName.Text);
                        Con.Append(";password=");
                        Con.Append(txtPassword.Text);
                        string strCon = Con.ToString();
                        updateAppConfigFile(strCon);
                        ConfigurationManager.RefreshSection("connectionStrings");
                        MessageBox.Show("Test connection succeeded.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                }
                else
                {
                    string strCon = Con.ToString();
                    updateAppConfigFile(strCon);
                    ConfigurationManager.RefreshSection("connectionStrings");
                    MessageBox.Show("Test connection succeeded.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

for exist in your application double click on the Cancel button and add given below code

private void Cancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Scot Tubergen
April 8, 2020 1:53 pm

tҺe website іѕ really good, I really like it!

1
0
Would love your thoughts, please comment.x
()
x