使用for循环获取列表框中的选定项目而不使用全局变量

Using for loop to get selected items in a listbox not working with global variable

我的列表框中有两个项目:

item1
item2

当我 select 第一项并单击按钮时,MessageBox 显示 item1。我单击确定,然后它会显示我需要的第二项。调试我的应用程序时,全局变量 "pattern" 仅显示第一个列表框项目,循环并再次显示相同的项目 (item1)。我需要它来显示 item1,然后显示 item2。我已经删除了这个例子的其他代码,但我的目标是让这个 for 循环捕获字符串中的列表框项目,然后调用一个方法,该方法将文件复制到基于列表框项目 selection 的文件夹,遍历每个项目并为每个 selected 项目复制其他文件。我遇到的问题是文件将被写入目标文件夹,然后我会收到一个文件已经存在的错误,因为它循环回到第一个项目。然后它应该 select 第二项并执行相同的操作,但复制方法实际上不会为列表中的第二项触发。

        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            pattern = (listBox1.SelectedItem.ToString());
            MethodToCopyFiles(); // This is my method used to copy files based on the selected item in the listbox.  
            listBox1.SetSelected(i, true);
            MessageBox.Show(listBox1.SelectedItem.ToString()); // Just here for my example, not intended for the application.
        }

您可以尝试以下方法。

    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        MessageBox.Show(listBox1.Items[i].ToString());
    }

如果是多选,您可以使用下面的代码检索所有选中的项目。

    foreach(int i in listBox1.SelectedIndices)
    {
        MessageBox.Show(listBox1.Items[i].ToString());
    }