Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用for循环获取列表框中不使用全局变量的选定项_C#_For Loop_Listbox - Fatal编程技术网

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

C# 使用for循环获取列表框中不使用全局变量的选定项,c#,for-loop,listbox,C#,For Loop,Listbox,我的列表框中有两项: item1 item2 当我选择第一个项目并单击按钮时,MessageBox显示item1。我单击ok,然后它会按我的需要显示第二项。调试我的应用程序时,全局变量“pattern”仅显示第一个列表框项,循环并再次显示同一项(item1)。我需要它来显示项目1和项目2。我已经删除了这个示例的其他代码,但我的目标是让这个for循环捕获字符串中的listbox项,然后调用一个方法,该方法将根据listbox项选择将文件复制到文件夹中,循环遍历每个项,并为每个选定项复制其他文件。

我的列表框中有两项:

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

        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
您可以尝试以下方法

    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());
    }