首页 文章

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

提问于
浏览
1

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

item1
item2

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

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.
        }

1 回答

  • 2

    您可以尝试以下方法 .

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

相关问题