Search code examples
c#wpfcomboboxtextboxfileinfo

Wrong Item Selected in Combo Box (C#, WPF)


Wrong Item Selected in Combo Box (C#, WPF)

I do have a comboBox and a textBox. When I select an item (html file) in my combo box, I would like to add the content into my text box. Here is what I've got so far:

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

Problem: When I select the second item, the third item's content is shown. Same happens everytime - does not matter which item I choose. When I choose the last item, the application is kicked: "Error: Index was out of range!"


Solution

  • Issue is you have added one dummy string "Please choose a file..." in items collection of your comboBox and added fileInfos collection items thereafter.

    So, if selectedIndex will be 1 that will point to 0th item in your collection. So, while fetching item from fileInfo collection, you need to get item from comboBox_DataPool.SelectedIndex - 1 index position.


    Change

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

    to

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