Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I tried to save the connection string in the App.confing file at the run time, then I opened the file during the application while it was running, and I found the connection string had been saved in the file, but after I closed the application the connection string had been deleted automatically.

Can you help me to keep the connection string in the app.config file? I added two textboxes to the form (txtServer and txtDatabase) and one button to connect to database when the user click it.

VB
Imports System.Data.SqlClient
Imports System.Text
Imports System.Configuration
Imports System.Xml

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        Dim strConnectionStringName As String = "con"
        Dim Con As StringBuilder = New StringBuilder("Data Source=")
        Con.Append(txtServer.Text)
        Con.Append(";Initial Catalog=")
        Con.Append(txtDatabase.Text)
        Con.Append(";Integrated Security=SSPI;")
        Con.Append("User ID=username; Password=xyz;")

        Dim ConStringSettings As New ConnectionStringSettings(strConnectionStringName, Con.ToString)
        Dim Config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        AddAndSaveOneConnectionStringSettings(Config, ConStringSettings)

        Catch ex As Exception
        MessageBox.Show(ConfigurationManager.ConnectionStrings("con").ToString() & _
            "This is invalid connection", "Incorrect server/Database.")
    End Try
End Sub

Public Sub AddAndSaveOneConnectionStringSettings(ByVal Config As Configuration, _
            ByVal ConStringSettings As ConnectionStringSettings)
    Dim ConStringsSection As ConnectionStringsSection = Config.ConnectionStrings
    ConStringsSection.ConnectionStrings.Add(ConStringSettings)
    Config.Save(ConfigurationSaveMode.Minimal)
    ConfigurationManager.RefreshSection("connectionStrings")
End Sub
End Class
Posted

1 solution

 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900