2016-03-31 61 views
0

我有一個公共字符串,我需要在整個程序中使用。傳遞方法之間的字符串值c#

public string connectionString = null; 

我指定值,如下:

internal string accessString() 
{ 
    return connectionString = 
     @"Provider=Microsoft.ACE.OLEDB.12.0;" + 
     @"Data Source=" + DBFileName + ";" + 
     @"Persist Security Info=False"; 
} 

當我運行的方法在第一時間值是正確的,但一旦方法執行完畢的值返回空值。

internal void selectDB() 
    { 
     try 
     { 
      OpenFileDialog choofdlog = new OpenFileDialog(); 
      choofdlog.Filter = "All Files (*.*)|*.*"; 
      choofdlog.FilterIndex = 1; 
      if (choofdlog.ShowDialog() == DialogResult.OK) 
      { 
       DBFileName = choofdlog.FileName; 
       connectionString = accessString(); 
       Saveproducts(); 
      } 
      MessageBox.Show(connectionString); 

     } 

     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    }//select db ends 

上述方法可以很好地得到值。

internal void writeContents()// read all the text files to the Data base 
    { 
     try 
     { 
      MessageBox.Show(connectionString); 
} 
} 

上面的這個方法返回null,即使它在第二個方法之後運行已經成功地爲connectionString賦值了。

我怎樣才能解決這個問題,我不想使用靜態

+1

請問您可以展示更多類的代碼嗎?你什麼時候調用'accessString()',什麼時候訪問'connectionString()'? –

+0

很難確切知道你做錯了什麼,但可能是由於對象超出範圍的某個實例 - 需要更多的代碼來確認,所有當前的答案都是推測性的(儘管使'connectionString'靜態可以工作,但可能會導致其他問題根據你的應用程序) – Charleh

回答

2

使用會話存儲的連接字符串,或者您可以使用

connectionString as Static variable 

,那麼它不會重置價值。

0

我怎樣才能改變這種做法,該方法在整個 程序

你能做到這一點創建此值,現在accessString總是返回有效的連接字符串。

public string connectionString = null; 
accessString(); 

internal string accessString() 
{ 
    return string.IsNullOrEmpty(connectionString)? 
     @"Provider=Microsoft.ACE.OLEDB.12.0;" + 
     @"Data Source=" + DBFileName + ";" + 
     @"Persist Security Info=False" : connectionString; 
} 
+0

你不能使用無效和返回的方法據我所知 –

+0

啊..我的壞,我忽略了它。謝謝@ChongChing現在正確。 –

相關問題