2010-11-23 8 views
1

In diesem CodeVerbindung ist nicht Fehler in catch-Block initialisiert

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(); 
      } 
     } 
    } 

die Verbindung nicht initialisiert Fehler gefangen ...

In der Datei app.config I

<?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> 
hatte

Was könnte das Problem sein

Antwort

1

Im Moment öffnen Sie nur die Verbindung (sConnection.Open();) innerhalb der try. Natürlich ist der wahrscheinlichste Ort, an dem eine Ausnahme auslösen wird, diese Zeile. In jedem Fall ist es sinnvoll, dass die Verbindung in der catch nicht unbedingt offen ist.

Und wenn das zugrunde liegende Problem dass der Aufruf von .Open() ist, versagt es gibt nicht viel, dass es tun können ...

Verwandte Themen