C#超出范围:将textFile内容生成到listBoxes

时间:2017-03-24 02:13:18

标签: c# winforms

我正在创建一个应用程序,它将从文本文件中获取文本文件路径,然后将它们加载到列表框中,当在列表框中单击时,文本文件内容将在名为textEditorControl1的脚本编辑器窗口小部件中生成。

事情是这样的。当我从列出文件夹名称的列表框中删除一个东西时,然后单击列表框中的另一个项目;它给了我一个错误:

  

未处理的类型' System.ArgumentOutOfRangeException'   发生在mscorlib.dll

     

其他信息:指数超出范围。必须是非负面的   并且小于集合的大小。

on string fullFileName2 = selectedScripts[listBox3.SelectedIndex];

    List<String> fullFileName;
    List<String> fullFileName2;
 List<string> selectedScripts = new List<string>();

        public void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex >= 0)
            {
                string fullFileName2 = selectedScripts[listBox3.SelectedIndex];
                textBox3.Text = fullFileName2;
                string File1 = fullFileName2;
                string text = System.IO.File.ReadAllText(File1);
                textEditorControl1.Text = text;
                textEditorControl1.Refresh();
            }
            else
            {

            }

        private void materialFlatButton10_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
            OpenFileDialog1.Multiselect = true;
            OpenFileDialog1.Filter = "Text Files|*.txt|All Files|*.*|Lua Files|*.lua";
            OpenFileDialog1.Title = "Select a Text/Lua File";
            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fullFileName2 = new List<String>(OpenFileDialog1.FileNames);


                foreach (string s in OpenFileDialog1.FileNames)
                {
                    listBox3.Items.Add(Path.GetFileName(s));
                    selectedScripts.Add(s);
                }


            }
        }



private void deleteFromListToolStripMenuItem_Click(object sender, EventArgs e)
    {
        label4.Text = " ";
        textBox3.Text = "";
        IDocument document = textEditorControl1.Document;
        document.Remove(0, document.TextLength);
        textEditorControl1.Refresh();
        selectedScripts.Clear();

        for (int i = listBox3.SelectedIndices.Count - 1; i >= 0; i--)
        {
            listBox3.Items.RemoveAt(listBox3.SelectedIndices[i]);
        }
    }

1 个答案:

答案 0 :(得分:1)

您正在清除SelectedScripts,然后当您点击某些内容时,您正尝试访问SelectedScripts中的索引listBox3.SelectedIndex中的项目,但此时SelectedScripts为空。

我认为你的删除方法应该是这样的:

private void deleteFromListToolStripMenuItem_Click(object sender, EventArgs e)
{
    label4.Text = " ";
    textBox3.Text = "";
    IDocument document = textEditorControl1.Document;
    document.Remove(0, document.TextLength);
    textEditorControl1.Refresh();

    for (int i = listBox3.SelectedIndices.Count - 1; i >= 0; i--)
    {
        selectedScripts.RemoveAt(listBox3.SelectedIndices[i]);
        listBox3.Items.RemoveAt(listBox3.SelectedIndices[i]);
    }
}

请注意,UI ListBox控件可以使用类,因此您可以将所有数据封装到一个添加到列表中的类对象中。