【问题标题】:Combobox crashes when selecting item with keyboard使用键盘选择项目时组合框崩溃
【发布时间】:2013-03-26 17:31:24
【问题描述】:

我对下面的代码有疑问,基本上是从存储扩展名为 .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();
        }
    }
}

【问题讨论】:

  • 请提供您获得的异常详细信息。
  • 您应该处理文件不完全是 10 行的情况。您无需在 obj 上调用 dispose,因为 using 会执行此操作。你能添加使用组合框的代码吗?

标签: c# combobox


【解决方案1】:

我的猜测是这可能是导致错误的原因:

cbTemplates.SelectedItem.ToString()

当您开始在组合框中输入内容时,SelectedItem 变为 null。

在尝试调用ToString() 之前,您应该测试cbTemplates.SelectedItem 是否为空。如果您尝试匹配组合框的文本,您可以尝试改用cbTemplates.Text

正如其他人对您的问题发表的评论一样,您无需在 using 内调用 Dispose,您应该考虑文件可能不包含 10 行的可能性..

【讨论】:

  • 非常感谢你们,我按照你们的建议做了(验证组合框是否为空),它工作得很好,但我离开了 .ToString() ,因为 .Text 误读了我的文件。无论如何,即使使用 .ToString() 当您验证您的应用程序显然不会崩溃时,它也会继续运行。再次感谢!!! ( if (cbTemplates.SelectedItem != null))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
  • 2012-05-17
  • 2011-01-13
相关资源
最近更新 更多