2014-10-09 38 views
1

我正在參加一個應用程序開發課程,我無法弄清楚在我的上下文中有什麼問題。任何人都可以請幫我嗎?我在與數據庫溝通方面有點新,所以我無法爲此提出解決方案。提前致謝!ConfigurationManager在當前上下文中不存在。我的代碼有什麼問題?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Data.SqlClient; 
using System.Configuration; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      String connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString; 

      using (SqlConnection sqlConnection = new SqlConnection(connectionString)) 
      { 
       try 
       { 
        if (sqlConnection.State == ConnectionState.Closed) 
         sqlConnection.Open(); 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.Message); 
       } 
    } 
     } 
    } 
} 

App.Config 

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
    <clear /> 
    <add name="NorthwindConnectionString" 
    providerName="System.Data.ProviderName" 
    connectionString="Server=localhost;Database=Northwind;Integrated Security=true;" /> 
    </connectionStrings> 

</configuration> 
+1

你一定要'System.Configuration.dll'參考? – 2014-10-09 19:42:38

+0

不,我對代碼發表了評論://在.NET中添加對System.Configuration的引用 然後我迷路了 – 2014-10-09 19:45:56

+0

那麼你是這麼做的? – 2014-10-09 19:46:26

回答

4

試試這個:

Menu Bar -> Project -> Add Reference... -> .NET (Tab) -> System.Configuration -> OK 

你應該確保你引用一個System.Configuration.dll

+0

是的,我認爲它會自動引用時,我添加「使用System.Configuration;」 – 2014-10-09 19:57:12

+0

@SamerElSabeh除非該DLL在GAC中。更多信息http://stackoverflow.com/questions/25643746/visual-studio-reference-of-dlls-are-automatically-created-at-bin-folder – 2014-10-09 20:00:53

+0

工作!謝謝:) – 2014-11-07 06:30:37

相關問題