我對下面的代碼有問題,基本上是從擴展名爲.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();
}
}
}
請提供您得到異常的詳細信息。 – Harrison 2013-03-26 17:35:08
當文件不完全是10行時,您應該處理這種情況。你不需要在'obj'上調用dispose,因爲'using'這樣做。你可以添加使用組合框的代碼嗎? – 2013-03-26 17:36:09