2014-05-21 24 views
5

我有一個通過使用這樣的數據層一個獲取數據以表格的應用程序:ConfigurationManager中的連接字符串爲空的用戶控件

public DataTable get(String query, ArrayList parameters = null) 
{    
    using (iDB2Connection cn = new iDB2Connection(ConfigurationManager.ConnectionStrings["iseries"].ToString())) 
    { 
     // get the data and return them  
    } 
} 

我有獲取數據,並能正常工作的形式。

不過,我創建了一個用戶控件它通過這種方法,當我跑我的項目,但它工作正常獲取數據,其中包含用戶控件拋出一個異常設計師的形式。

「爲了防止加載設計之前可能會丟失數據時, 以下錯誤必須得到解決:」

我發現錯誤位於從<appSettings>連接字符串的檢索。

它拋出一個nullpointerexception。

但只限於設計模式。當我忽略它時,一切正常,但是,我想知道如何解決這個問題。

通過我的用戶訪問他們時,爲什麼我的<appSettings>空?

更新1

看來我的用戶無法識別<appSettings>可言。

當我把這段代碼放在我的UserControl Load事件中時,我也得到一個nullreference。

private void SelectUser_Load(object sender, EventArgs e) 
{    
    txtLocation.Text = ConfigurationManager.AppSettings["location"].ToString(); 
} 
+0

這是ASP.NET,的WinForms,還是什麼? –

+0

這是winforms,我添加了標籤。 – randomizer

+0

你能夠從任何其他地方*讀取*連接字符串值嗎? – Kurubaran

回答

2

我找到了解決辦法,在將designMode用戶控件已經執行的Load事件的代碼。 由於App.config在設計模式中不可用,因此未找到並因此未加載。 所以我做了它周圍的小檢查,檢查中的designMode與否:

bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime); 
if (designMode) 
{ 
    string location = ConfigurationManager.AppSettings["location"].ToString(); 
} 
0

我想你只需要調整你如何取得你的ConnectionString

using (iDB2Connection cn = new iDB2Connection(ConfigurationManager.ConnectionStrings["iseries"].ConnectionString) 
{ 
    //get the data and return them  
} 
+0

不,仍然得到「對象引用未設置爲對象的實例」。出於某種原因,ConfigurationManager設置在用戶控件中爲空。 – randomizer

1

下面的文章描述了WPF/Win Forms中的這個問題。請看看...

MS Forum

相關問題