使用键盘选择项目时,Combobox会崩溃

时间:2013-03-26 17:31:25

标签: c# combobox

我对下面的代码有疑问,基本上是从存储扩展名为.config的文件的路径中读取的内容,它读取没有扩展名的文件的名称,并将它们全部显示在组合框中。这工作正常,如果你单击向下箭头并选择一个名称,它实际上做了它应该的,但是,一旦我用鼠标从下拉列表中选择了一个项目,我回去开始在组合框内输入我的应用程序崩溃抛出异常。

我尝试添加一个try-catch-finally,但它仍然会抛出相同的错误。一旦我开始输入组合框,可能是导致我的应用程序崩溃的循环吗?

Pd积。如果我只是使用鼠标从下拉菜单中选择一个项目我的应用程序工作正常但是一旦我用鼠标选择了一个项目并使用键盘在组合框内键入另一个项目名称我的应用程序崩溃。任何指针都会有所帮助。

// 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();
        }
    }
}

1 个答案:

答案 0 :(得分:4)

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

cbTemplates.SelectedItem.ToString()

当您开始输入组合框时,SelectedItem将变为空。

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

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