简体   繁体   中英

Changing ConnectionString for SQL Server in C# application

I have created application for displaying and rendering reports from SQLServer to pdf/doc/xls. Because I need to change ConnectionString on Runtime, I ask user for input values on runtime. So, after hours of searching thousands of sites, I found different solutions but none of them works for me.

I place connection changing in one of my methods as shown below.

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove("MapSoftRPTConnectionString");
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("MapSoftRPTConnectionString", Parameters.ConnectionString()));
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

I have default string and with it, all works fine on my machine. When I (as user) intentionally insert bad values, it is still working. So, it doesn't take into the account my changes.

What is going on?

EDIT:

I don't need to save it to config, but all what I want is to make user be able to change server and account when creating reports at runtime. Process that is know implemented is as follows:

// .........
// get parameters from user input and store them in variables

// then change connection string
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["MapSoftRPT.Properties.Settings.MapSoftRPTConnectionString"].ConnectionString = @Parameters.ConnectionString();
config.Save(ConfigurationSaveMode.Modified);

// then start rendering report
this.reportViewer1.Reset();
this.reportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local;

this.reportViewer1.LocalReport.ReportPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Parameters.getReportRDLCName(repType);
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource(Parameters.getReportDataSource(repType), Parameters.getReportDataTable(repType)));

bytes = reportViewer1.LocalReport.Render("PDF"); // and send it to FileStream...

I'm not sure if there is a specific reason that you need to save it to the config.connection strings, but if not... have you tried,

string Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";

if it needs to be global, you could create a public class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM