catch块中的连接未初始化错误

时间:2010-11-23 06:37:23

标签: c# visual-studio

在此代码中

    private void btnConnect_Click(object sender, EventArgs e)
    {
        string localHost = "192.168.10.3";
        string logInDetails = "gp";
        SqlConnection sConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

        try
        {

            //Checking for the Valid entries in textboxes.
            if ((txtPassword.Text == logInDetails) && (txtUsername.Text == logInDetails))

                //Checking for the appropriate local server address.
                if (txtHost.Text == localHost)
                {
                    sConnection.Open();
                    BindDBDropDown();
                    SetOperationDropDown();
                    PrimaryKeyTable();
                    lblError.Text = "You are connected to the SQL Server....";
                }
                else
                {
                    lblError.Text = "Invalid Credentials";
                }

        }
        catch (Exception ex)
        {
            //All the exceptions are handled and written in the EventLog.
            EventLog log = new EventLog("Application");
            log.Source = "MFDBAnalyser";
            log.WriteEntry(ex.Message);
        }
        finally
        {
            //To close the connection
            if (sConnection != null)
            {
                sConnection.Close();
            }
        }
    }

连接未初始化错误被捕获...

在app.config文件中我有

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Data Source=192.168.10.3;InitialCatalog=GoalPlanForTrainees;userid=gp;password=gp"/>
  </appSettings>
</configuration>

可能是什么问题

1 个答案:

答案 0 :(得分:1)

目前您只打开sConnection.Open();内的连接(try)。当然,异常抛出的最可能的地方是这一行。无论哪种方式,都可以在catch中打开连接。

如果潜在的问题 .Open()的调用失败,那么可以执行的内容并不多......