2013-03-26 53 views
1

我對下面的代碼有問題,基本上是從擴展名爲.config的文件的存儲路徑中讀取的,它讀取沒有擴展名的文件的名稱並將它們全部顯示在一個組合框中。這工作正常,如果你點擊向下箭頭,選擇一個名稱,它實際上做它應該的,但是,一旦我從鼠標的下拉菜單中選擇一個項目,我回去,並開始在組合框內打字我的應用程序崩潰拋出異常。組合框在使用鍵盤選擇項目時崩潰

我試着添加一個try-catch-finally但它一直拋出相同的錯誤。一旦我開始在組合框中輸入,會不會導致我的應用程序崩潰?

p.d.如果我只是使用鼠標從下拉菜單中選擇一個項目,我的應用程序可以正常工作,但是一旦我用鼠標選擇了一個項目並使用鍵盤在組合框內鍵入另一個項目名稱,我的應用程序就會崩潰。任何指針都會有幫助。

// Gets all the file names from the path assigned to templatePath 
// and assigns it to the string array fname 
string[] fname = Directory.GetFiles(templatePath); 

// Begin sorting through the file names assigned to the string array fname 
foreach (string file in fname) 
{ 
    // Remove the extension from the file names and compare the list with 
    // the dropdown selected item 
    if (System.IO.Path.GetFileNameWithoutExtension(file) == cbTemplates.SelectedItem.ToString()) 
    { 
     // StreamReader gets the contents from the found file and assigns 
     // them to the labels 
     using (var obj = new StreamReader(File.OpenRead(file))) 
     { 
      lbl1.Content = obj.ReadLine(); 
      lbl2.Content = obj.ReadLine(); 
      lbl3.Content = obj.ReadLine(); 
      lbl4.Content = obj.ReadLine(); 
      lbl5.Content = obj.ReadLine(); 
      lbl6.Content = obj.ReadLine(); 
      lbl7.Content = obj.ReadLine(); 
      lbl8.Content = obj.ReadLine(); 
      lbl9.Content = obj.ReadLine(); 
      lbl10.Content = obj.ReadLine(); 
      obj.Dispose(); 
     } 
    } 
} 
+2

請提供您得到異常的詳細信息。 – Harrison 2013-03-26 17:35:08

+2

當文件不完全是10行時,您應該處理這種情況。你不需要在'obj'上調用dispose,因爲'using'這樣做。你可以添加使用組合框的代碼嗎? – 2013-03-26 17:36:09

回答

4

我的猜測是這可能會導致錯誤:

cbTemplates.SelectedItem.ToString() 

當您在組合框中開始打字,則變成的SelectedItem空。

您應該在嘗試調用ToString()之前測試cbTemplates.SelectedItem是否爲空。如果您嘗試匹配組合框的文本,則可以嘗試使用cbTemplates.Text

正如在你的問題發表了評論,你不需要調用Disposeusing,你應該考慮的是,文件可能不包含10日線的可能性..

+0

非常感謝你們,我按照你的建議(驗證了組合框是否爲空),它工作得很好,但我離開了.ToString(),因爲.Text誤讀了我的文件。無論如何,即使使用.ToString(),當您驗證您的應用程序顯然不會崩潰時,它仍會繼續。再次感謝!!! (if(cbTemplates.SelectedItem!= null)) – hectormtnezg 2013-03-26 19:50:27