如何修复此IndexOutOfBoundsException

我的程序运行正常,但有一点问题。 当我将新曲目以前存在的文件添加到ListBox时,程序会遇到错误。 代码似乎不愿意在一个在不同时间添加的新文件中进行循环。 请帮我。 谢谢 ….

public partial class Form1 : Form { //... string[] files, paths; private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { files = openFileDialog1.SafeFileNames; paths = openFileDialog1.FileNames; for (int i = 0; i < files.Length - 1; i++) { listBox1.Items.Add(files[i]); } } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { axWindowsMediaPlayer1.URL = paths[listBox1.SelectedIndex]; } } 

阿迪尔已经找到了问题的原因,但有一个更清洁的解决方案:

 foreach (string file in files) { listBox1.Items.Add(file); } 

……甚至更好:

 listBox1.Items.AddRange(files); 

事实上,我会更进一步,完全摆脱实例变量filespaths 。 我要么使用Tuple要么为文件/类对创建一个类。 然后,您可以将每个完整数据项添加到listBox1.Items ,设置DisplayMember以便显示file部分,但是当更改所选索引时,从所选项中获取路径 。 然后根本不需要乱用索引。

您正在添加一个文件少于文件存在的文件,当您将访问最后一个文件时

更改

 for (int i = 0; i < files.Length - 1; i++) { listBox1.Items.Add(files[i]); } 

 for (int i = 0; i < files.Length; i++) { listBox1.Items.Add(files[i]); } 

根据OP的评论进行编辑

您可以通过单击button1将列表框中的文件多次添加一次。 这将在列表框中添加新文件,但是数组将丢失数组中的先前项目,并且数组中的计数将变得小于列表框中的项目。

 private void button1_Click(object sender, EventArgs e) { listBox1.Items.Clear(); //Clear the items of list box to keep the same items in both listbox and in array paths. if (openFileDialog1.ShowDialog() == DialogResult.OK) { files = openFileDialog1.SafeFileNames; paths = openFileDialog1.FileNames; for (int i = 0; i < files.Length ; i++) { listBox1.Items.Add(files[i]); } } } 

如果你想保留以前的选择,那么使用list而不是数组,因为list可以比数组更容易增长。

 string[] files; List paths = new List() ; private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { files = openFileDialog1.SafeFileNames; paths.AddRange(openFileDialog1.FileNames.ToList()); for (int i = 0; i < files.Length; i++) { listBox1.Items.Add(files[i]); } } } 

我认为问题不在于向数组中添加项目。 更可能的原因是SelectedIndexChanged事件处理程序。 您应该检查SelectedIndex以确保它是有效的。

 int idx = listBox1.SelectedIndex; if (paths != null && idx > 0 && idx < paths.Length) { axWindowsMediaPlayer1.URL = paths[idx]; } 

我认为Jon和Adil都是绝对正确的,你绝对可以使用他们的代码来解决部分问题。 但是,我的猜测是你在paths没有任何元素,所以当你试图从中获取一个元素时,它会抛出exception。 你可以试试下面的代码:

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (paths.Length >= listBox1.SelectedIndex) axWindowsMediaPlayer1.URL = paths[listBox1.SelectedIndex]; } 

看看你是否仍然被抛出exception,如果没有,那么你还有另外一个问题,即为什么你的paths变量没有设置,或者为什么列表框选择的索引大于变量中的元素。