您好我正在编写一个 WinForm 应用程序,我希望我的用户在运行应用程序时选择服务器和数据库。所以我有这个代码:
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(textBox1.Text);
Con.Append(";Initial Catalog=");
//Con.Append(";AttachDbFilename=");
Con.Append(textBox2.Text);
Con.Append(";Integrated Security=true;");
string str = Con.ToString();
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//the full name of the connection string can be found in the app.config file
// in the "name" attribute of the connection string
config.ConnectionStrings.ConnectionStrings["con"].ConnectionString = str;
//Save to file
config.Save(ConfigurationSaveMode.Modified);
//force changes to take effect so that we can start using
//this new connection string immediately
ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.Name);
Properties.Settings.Default.Reload();
using (SqlConnection con = new SqlConnection(WF_AbsPres.Properties.Settings.Default.con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from TypeofUseName", con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "TypeofUse_code";
}
我的 app.config 文件是这样的:
<connectionStrings>
<add name="con"
connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
很明显con
,我的settings
文件中有初始值为 null 的文件。
当我运行代码时,它说您必须为连接字符串提供初始值。怎么了 ?我错过了什么吗?(我放comboBox只是为了测试连接)