在运行时更改连接字符串

时间:2013-09-14 18:01:02

标签: c# connection-string app-config

您好我正在编写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只是为了测试连接)

0 个答案:

没有答案