【问题标题】:The ConnectionString property has not been initialized bugConnectionString 属性未初始化错误
【发布时间】:2018-07-30 17:38:35
【问题描述】:

好吧,我似乎遇到了一个烦人的错误,希望您能帮助我。

我正在使用 winforms,并且在应用程序设置表单上,我提供了更改连接字符串的功能。当连接字符串的不同部分发生更改并且用户离开文本框时,它会将信息写入 app.config。这一切都像一个魅力。

我有一个按钮来测试连接,所以当连接字符串被更改后在表单仍然打开时按下它时,我遇到了一个错误:

The ConnectionString property has not been initialized

为了使这更复杂一点,当我关闭并重新打开应用程序时,相同的表单现在能够建立连接并且一切顺利。几乎就好像 Config 在进行更改后将自己锁定以防被查询。

在更改 app.config 和尝试使用存储的连接字符串打开连接之间我需要做些什么。

这是我更改 app.config 的代码:

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     config.ConnectionStrings.ConnectionStrings["myconnstr"].ConnectionString = textboxCS.Text;
        config.Save(ConfigurationSaveMode.Modified);

这是我测试连接的代码:

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        string constr = System.Configuration.ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(constr))
        {
            try
            {
                connection.Open();
                connection.Close();
                MessageBox.Show("Successful Connection");
            }
            catch (Exception ee)
            {
                ee.ToString();
                MessageBox.Show("Failed Connection");
            }
            finally
            {
                connection.Close();
            }

【问题讨论】:

  • 尝试过使用 ConStr 这样的单字键而不是 Clock_Card.Properties.Settings.HH_ClockCardConnectionString
  • 您是否收到“连接失败”消息? using 语句在异常处理程序之外,因此我认为您实际上并没有到达 connectionOpen。构造函数失败,我认为这意味着连接已经打开。
  • @jdweng 好的,所以,在调试时,我可以进入 connection.Open();但这就是它遇到异常的地方
  • @PrashantPimpale 我已经编辑了代码以反映正确的连接字符串名称
  • @StuartBlack 这段代码是否在不同的类库中?

标签: c# app-config


【解决方案1】:

这个:

string constr = System.Configuration.ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString; 

需要替换为:

string constr = config.ConnectionStrings.ConnectionStrings["myconnstr"].ConnectionString;

问题是它试图打开 ConfigurationManager 两次

感谢大家的帮助

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多