1

I have a problem on my music player C# application, If I add new files using open file dialogue. The array is not adding the new files. Then it will show the Selected Index Array Index out of bound exception error on player.URL = path[track_list.SelectedIndex]; on the following line. So how to handle this exception ? How to update the new elements on the array ?

string[] files, path;

        private void Track_list_SelectedIndexChanged(object sender, EventArgs e)
        {
        
            player.URL = path[track_list.SelectedIndex];
    }

 private void Btn_import_Click_1(object sender, EventArgs e)
        {
        //ofd is the instance of open file dialogue
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //add the file name into two arrays
                files = ofd.SafeFileNames;
                path = ofd.FileNames;

                for (int i=0; i<files.Length; i++)
                {
                //add songs into the items box
                    track_list.Items.Add(files[i]); 
                }
                
            }
        }
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • Did you ever instantiate the array and assign it a size? – Chris Cudmore Jul 29 '21 at 17:10
  • 1
    Please debug your code and [edit] question with at least following: value of `track_list.SelectedIndex` when it fails, content of `path` when it fails, content of `path` after `Btn_import_Click_1` as well as in which order Btn_import_Click_1 and Track_list_SelectedIndexChanged hit during debugging. – Alexei Levenkov Jul 29 '21 at 17:14
  • `path = ofd.FileNames;` this seems fishy to me. `path = ofd.FileNames.ToList()` would guarantee you are working with path and not a discarded collection. – Felix Castor Jul 29 '21 at 17:25
  • @FelixCastor How converting an array (FileNames) to a List would be useful? Not exactly sure what problem you trying to solve with your comment. – Alexei Levenkov Jul 29 '21 at 19:01
  • @Alexi Levenkov, `ofd` is the dialog window and by setting `path = ofd.FileNames` you are assigning a reference to a collection owned by `ofd`. If afterwards `ofd` disposes of the `FileNames` array then it also disposes of `path`. Calling the `ToList()` creates a new collection. Notice the other method references 'path' which leads me to believe it is a property that sticks around after the dialog has been closed. – Felix Castor Jul 30 '21 at 13:05

0 Answers0