使用键盘选择项目时,组合框崩溃
本文关键字:组合 崩溃 项目 键盘 选择 | 更新日期: 2023-09-27 18:06:11
我对下面的代码有一个问题,基本上它所做的是从存储扩展名为.config的文件的路径中读取,它读取没有扩展名的文件的名称并将它们全部显示在一个组合框中。这工作得很好,如果你点击向下箭头并选择一个名称,它实际上做了它应该做的,然而,一旦我用鼠标从下拉菜单中选择了一个项目,我返回并开始在组合框中输入,我的应用程序崩溃并抛出异常。
我试过添加一个try-catch-finally,但它一直抛出相同的错误。当我开始在组合框中输入时,可能是循环导致我的应用程序崩溃吗?
申先生。如果我只是用鼠标从下拉菜单中选择一个项目,我的应用程序可以正常工作,但一旦我用鼠标选择了一个项目,并使用键盘在组合框中输入另一个项目名称,我的应用程序就会崩溃。任何提示都会有帮助的。
// 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变为null。
在尝试调用ToString()
之前,您应该测试cbTemplates.SelectedItem
是否为null。如果你想匹配组合框的文本,你可以尝试使用cbTemplates.Text
代替。
正如其他人对你的问题的评论,你不需要在using
中调用Dispose
,你应该考虑文件可能不包含10行的可能性。