Skip to content

System.IndexOutOfRangeException #1

@kotomafia

Description

@kotomafia

Hello! I'm found a bug in your program. If you will add songs more than one try, your code in

private void listBoxSongs_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Write a code to play music
            axWindowsMediaPlayerMusic.URL = paths[listBoxSongs.SelectedIndex];
        }

will call the exception System.IndexOutOfRangeException,
photo_2024-09-01_12-06-39
because your String array paths is clearning every time, when you click on button SelectSongs, while your listBoxSongs updated.

I'm fixed this trouble by the way of change your array to collection List:

public partial class MusicPlayerApp : Form
{
    public MusicPlayerApp()
    {
        InitializeComponent();
    }

    List<string> paths = new List<string>();
    List<string> files = new List<string>();

    private void btnSelectSongs_Click(object sender, EventArgs e)
    {
        //Code to SElect Songs
        OpenFileDialog ofd = new OpenFileDialog();
        //Code to select multiple files
        ofd.Multiselect = true;
        if(ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
        {
            files.AddRange(ofd.SafeFileNames);
            paths.AddRange(ofd.FileNames);
            //Display the music titles in listbox
            foreach (var file in ofd.SafeFileNames)
            {
                listBoxSongs.Items.Add(file);
            }
        }
    }

    private void listBoxSongs_Click(object sender, EventArgs e)
    {
        if (listBoxSongs.SelectedIndex >= 0 && listBoxSongs.SelectedIndex < paths.Count)
        {
            axWindowsMediaPlayerMusic.URL = paths[listBoxSongs.SelectedIndex];
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions