-1

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!"

sjantke
  • 605
  • 4
  • 9
  • 35

1 Answers1

0

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);
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • It seems to work. Unfortunately, when I click on the first item "Please choose a file...", it throws the same exception. – sjantke Jul 20 '14 at 19:04
  • 1
    0th index should not get past to your else statement. It should been handled in first if condition. Not sure why not but instead of checking string you can check for SelectedIndex like this - `if (comboBox_DataPool.SelectedIndex == 0) { textBox_Text.Text = string.Empty; }`. – Rohit Vats Jul 20 '14 at 19:14