2013-03-26 79 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