Reputation: 11
I'm using a WinForm form created with C # to connect to a Sql server database.
To connect to the database the user must provide a login and a password.
I use the configuration file App.config to store the connectionString as following :
<ConnectionStrings>
<Add name = "K1" connectionString = "Data Source = HP; Initial Catalog = TRVANALYT; User ID = {0}; Password = {1}
ProviderName = "System.Data.SqlClient" />
</ ConnectionStrings>
The problem that is posed to me does not save a new connectionString
.
to refresh connextionString K1 I must rebuild the program and it gives the right result
If you have suggestions
What's the best practice?
thank you very much
My Code :
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string connexionstring = ConfigurationManager.ConnectionStrings["K1"].ToString();
var connectionStringsSection = (ConnectionStringsSection) config.GetSection("connectionStrings");
string NewConnexionstring = string.Format(connexionstring, txtUser.Text, txtPwd.Text);
connectionStringsSection.ConnectionStrings["K1"].ConnectionString = NewConnexionstring; //Set new connectionString with user and password
connectionStringsSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("connectionStrings");
App.config
<configSections>
</configSections>
<connectionStrings>
<add name="K1" connectionString="Data Source=HP;Initial Catalog=TRVANALYT;User ID={0};Password={1}" providerName="System.Data.SqlClient" />
</connectionStrings>
Upvotes: 1
Views: 670
Reputation: 11
I have the same problem, but when I debug, I realize that the ConnectionString was saved, but when I create a new object, the Connectionstring of this is false. I fix that by this way:
Code
public partial class QuanLySieuThiEntities : DbContext
{
//This is the default constructor
public QuanLySieuThiEntities()
: base("name=QuanLySieuThiEntities")
{
}
//Add this constructor
public QuanLySieuThiEntities(String connString)
: base(connString)
{
}
}
Code
string _conString = System.Configuration.ConfigurationManager.ConnectionStrings["QuanLySieuThiEntities"].ConnectionString;
QuanLySieuThiEntities newObject = new QuanLySieuThiEntities(_conString);
Upvotes: 1