Skip to main content
 首页 » 编程设计

c#之使用键盘选择项目时组合框崩溃

2024年02月13日10tuyile006

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

请您参考如下方法:

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

cbTemplates.SelectedItem.ToString() 

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

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

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