【问题标题】:Wrong Item Selected in Combo Box (C#, WPF)在组合框中选择了错误的项目(C#,WPF)
【发布时间】:2014-07-20 18:02:28
【问题描述】:

在组合框中选择了错误的项目(C#、WPF)

我确实有一个comboBox 和一个textBox。当我在组合框中选择一个项目(html 文件)时,我想将内容添加到我的文本框中。这是我到目前为止所得到的:

public void SetDataPoolToComboBox()
    {
        comboBox_DataPool.Items.Clear();

        comboBox_DataPool.Items.Add("Please choose a file...");
        comboBox_DataPool.SelectedIndex = 0;

        if (true == CheckPath())
        {
            foreach (string s in Directory.GetFiles(pathTexts, "*.html"))
            {
                comboBox_DataPool.Items.Add(Path.GetFileNameWithoutExtension(s));
            }
        }
    }

public void comboBox_DataPool_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SetContentToTextBox();
    }

    public void SetContentToTextBox()
    {
        if (true == CheckPath())
        {
            FileInfo[] fileInfo = directoryInfo.GetFiles("*.html");
            if (fileInfo.Length > 0)
            {
                if (comboBox_DataPool.Text == "Please choose a file..." || comboBox_DataPool.Text == "")
                {
                    textBox_Text.Text = string.Empty;
                }
                else
                {
                    StreamReader sr = new StreamReader(fileInfo[comboBox_DataPool.SelectedIndex].FullName, Encoding.UTF8);
                    textBox_Text.Text = sr.ReadToEnd();
                    sr.Close();
                }
            }
        }
    }

问题:当我选择第二个项目时,会显示第三个项目的内容。每次都会发生同样的情况 - 我选择哪个项目无关紧要。当我选择最后一项时,应用程序被踢:“错误:索引超出范围!”

【问题讨论】:

    标签: c# wpf combobox textbox fileinfo


    【解决方案1】:

    问题是您在组合框的项目集合中添加了一个虚拟字符串“请选择一个文件...”,然后添加了 fileInfos 集合项目。

    因此,如果 selectedIndex 为 1,则将指向集合中的第 0 个项目。因此,在从 fileInfo 集合中获取项目时,您需要从comboBox_DataPool.SelectedIndex - 1 索引位置获取项目。


    改变

    StreamReader sr = new StreamReader(fileInfo[comboBox_DataPool.SelectedIndex]
                                        .FullName, Encoding.UTF8);
    

    StreamReader sr = new StreamReader(fileInfo[comboBox_DataPool.SelectedIndex - 1]
                                        .FullName, Encoding.UTF8);
    

    【讨论】:

    • 它似乎有效。不幸的是,当我单击第一项“请选择文件...”时,它会引发相同的异常。
    • 第 0 个索引不应超过您的 else 语句。应首先处理 if 条件。不知道为什么不检查字符串,你可以像这样检查 SelectedIndex - if (comboBox_DataPool.SelectedIndex == 0) { textBox_Text.Text = string.Empty; }.
    猜你喜欢
    • 1970-01-01
    • 2013-12-27
    • 2013-08-06
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多